フィルターのクリア

How to count the number of occurrences of each pair in a cell?

3 ビュー (過去 30 日間)
Md Shahidullah Kawsar
Md Shahidullah Kawsar 2018 年 10 月 30 日
編集済み: Akira Agata 2018 年 10 月 31 日
Suppose I have a cell array
C = {[1; 2; 3]; [1; 2; 3; 4]; [1; 2]};
c{:}
ans =
1
2
3
ans =
1
2
3
4
ans=
1
2
% where any digit won't repeat in the individual cell.
I need to find out the number of occurrences of each pair. Expected output:
Pair(1,2) = 3 occurences;
Pair(1,3) = 0;
Pair(1,4) = 0;
Pair(2,1) = 0;
Pair(2,3) = 2;
Pair(2,4) = 0;
Pair(3,1) = 0;
Pair(3,2) = 0;
Pair(3,4) = 1;
How can I find it?
  2 件のコメント
Rik
Rik 2018 年 10 月 30 日
What code have you tried so far? It looks like there is a simple, naive approach with some loops that would solve it (not sure if there are some tricks you can pull to speed it up substantially).
Md Shahidullah Kawsar
Md Shahidullah Kawsar 2018 年 10 月 31 日
編集済み: Md Shahidullah Kawsar 2018 年 10 月 31 日
I was trying this code for the array A = [1 2 3; 2 3 1; 2 1 3]
for n = 2:3
[j,i]=ind2sub(fliplr(size(A)), strfind(reshape(A.',1,[]),[1 n]).');
C = [i,j];
d = numel(C(j));
T9 = table(1, n, d)
end
but it has 2 problems: (1) error occurs when the second row ends with 1 and the third row begins with 2. (2) for cell array, this code doesn't work

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

採用された回答

Akira Agata
Akira Agata 2018 年 10 月 31 日
編集済み: Akira Agata 2018 年 10 月 31 日
I think one possible way would be like this:
c = {[1; 2; 3]; [1; 2; 3; 4]; [1; 2]};
Pair = [repelem((1:4)',4,1),repmat((1:4)',4,1)];
Count = zeros(size(allPair,1),1);
for kk = 1:numel(c)
d = [c{kk}(1:end-1),c{kk}(2:end)];
[~,lo] = ismember(d,Pair,'rows');
Count = Count + (histcounts(lo,1:size(Pair,1)+1))';
end
T = table(Pair,Count);
The output is:
>> T
T =
16×2 table
Pair Count
______ _____
1 1 0
1 2 3
1 3 0
1 4 0
2 1 0
2 2 0
2 3 2
2 4 0
3 1 0
3 2 0
3 3 0
3 4 1
4 1 0
4 2 0
4 3 0
4 4 0

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by