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

cell arrayspair count

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?

Best Answer

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