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

3 次查看(过去 30 天)
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
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 CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by