Effacer les filtres
Effacer les filtres

Combine columns of a matrix based on equality

4 vues (au cours des 30 derniers jours)
Koren Murphy
Koren Murphy le 30 Nov 2020
Commenté : Ameer Hamza le 30 Nov 2020
I have a matrix of 1's and 0's and I would like to combine any column that repeats itself in the matrix - e.g if a is the matrix below I want b be the combination of any columns that are the same so b would be as shown - a new matrix with a combined repeated columns added togtehr and none repated ones left the same.
a = [1 1 1 0;1 0 0 0;0 0 0 1;1 1 1 0; 0 0 0 1]
b = [2 2 2 0; 1 0 0 0; 0 0 0 2];
The matrix I am actually dealing with is very large this is just a simplified version.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 30 Nov 2020
Try this
a = [1 1 1 0;1 0 0 0;0 0 0 1;1 1 1 0; 0 0 0 1];
b = [2 2 2 0; 1 0 0 0; 0 0 0 2];
[M, ~, idx] = unique(a, 'rows', 'stable');
mul = histcounts(idx, 'BinMethod', 'integers').';
M = M.*mul;
Result
>> M
M =
2 2 2 0
1 0 0 0
0 0 0 2
  3 commentaires
Koren Murphy
Koren Murphy le 30 Nov 2020
Also apoliges for the confusion it was my explanation that was at error here! The true example is:
a = [1 0 1 1; 1 0 1 0; 0 1 0 1];
so b should be
b = [2 0 1;2 0 0;0 1 1]
many thanks!
Ameer Hamza
Ameer Hamza le 30 Nov 2020
The logic is same. Just a little modification is needed
a = [1 0 1 1; 1 0 1 0; 0 1 0 1];
b = [2 0 1;2 0 0;0 1 1];
[M, ~, idx] = unique(a.', 'rows', 'stable');
mul = histcounts(idx, 'BinMethod', 'integers');
M = M.'.*mul;

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by