Clear Filters
Clear Filters

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

2 views (last 30 days)
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 Comments
Rik
Rik on 30 Oct 2018
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 on 31 Oct 2018
Edited: Md Shahidullah Kawsar on 31 Oct 2018
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

Sign in to comment.

Accepted Answer

Akira Agata
Akira Agata on 31 Oct 2018
Edited: Akira Agata on 31 Oct 2018
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

More Answers (0)

Categories

Find more on Matrices and 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!