How to compare each element of an array with the rest of the elements for several rows independently?

1 回表示 (過去 30 日間)
I want to compare each element of an array with the rest of the elements (in a single row of a matrix) and identify which pair(s) of indexes have both values of 1 (in each row). 'nchoosek' works for one row, but when other rows are added like the following example, the code does not work. It is expected the results of each row is independent of other rows.
A =[1 1 0 1 1 0; 0 0 1 0 0 1; 0 0 0 1 1 1; 1 1 1 1 1 1];
for i=1:4
index_matrix(i,:,:) = nchoosek(find(A(i,:)==1),2)
end;

採用された回答

Stephen23
Stephen23 2019 年 4 月 13 日
Because each array has a different size you will have to use a cell array:
A = [1 1,0,1,1,0;0,0,1,0,0,1;0,0,0,1,1,1;1,1,1,1,1,1];
N = size(A,1);
C = cell(1,N);
for k = 1:N
V = find(A(k,:));
C{k} = nchoosek(V,2);
end
giving:
>> C{:}
ans =
1 2
1 4
1 5
2 4
2 5
4 5
ans =
3 6
ans =
4 5
4 6
5 6
ans =
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
>>
See also:
  2 件のコメント
Mohammad Fazelpour
Mohammad Fazelpour 2019 年 4 月 16 日
Now, I want to access the cell array, C, and identify how many times different indexes have occurred. For example, in the case of above example, the output would be
Cell Array # of times
1 2 2
1 3 1
1 4 2
......
5 6 2
I wrote this
[row, column] = size(C)
for i=1:4
Sum (i) = cellfun(@(x) find(x=='1 2'), C);
end
which is not correct. Your help is appreciated.
Stephen23
Stephen23 2019 年 4 月 17 日
>> M = vertcat(C{:});
>> [U,~,X] = unique(M,'rows');
>> N = histc(X,1:max(X));
>> [U,N]
ans =
1 2 2
1 3 1
1 4 2
1 5 2
1 6 1
2 3 1
2 4 2
2 5 2
2 6 1
3 4 1
3 5 1
3 6 2
4 5 3
4 6 2
5 6 2

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by