Combine columns of a matrix based on equality

1 回表示 (過去 30 日間)
Koren Murphy
Koren Murphy 2020 年 11 月 30 日
コメント済み: Ameer Hamza 2020 年 11 月 30 日
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.

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 11 月 30 日
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 件のコメント
Koren Murphy
Koren Murphy 2020 年 11 月 30 日
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 2020 年 11 月 30 日
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;

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by