Combine columns of a matrix based on equality

1 view (last 30 days)
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.

Accepted Answer

Ameer Hamza
Ameer Hamza on 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 Comments
Koren Murphy
Koren Murphy on 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 on 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;

Sign in to comment.

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!