MATLAB: How to count the top five pairs (for each digit) which have the highest number of occurrences in a cell array

cell arrayhighest occurrencespair count

Suppose I have a cell array
C = {[1; 3; 5; 4; 6]; [1; 2; 3; 4; 5; 6; 7]; [1; 4; 3; 6]};
c{:}
ans =
1
3
5
4
6
ans =
1
2
3
4
5
6
7
ans=
1
4
3
6
% where any digit won't repeat in the individual cell.
For each digit, I need find out the top five pairs which have the highest number of occurrences. Expected Output:
Pair(1,2) = 1
Pair(1,3) = 1
Pair(1,4) = 1
Pair(1,5) = 0
Pair(1,6) = 0
Pair(2,3) = 1
Pair(2,1) = 0
Pair(2,4) = 0
Pair(2,5) = 0
Pair(2,6) = 0
Pair(3,4) = 1
Pair(3,5) = 1
Pair(3,6) = 1
Pair(3,1) = 0
Pair(3,2) = 0
Pair(4,3) = 1
Pair(4,5) = 1
Pair(4,6) = 1
Pair(4,1) = 0
Pair(4,2) = 0
Pair(5,4) = 1
Pair(5,6) = 1
Pair(5,1) = 0
Pair(5,2) = 0
Pair(5,3) = 0
Pair(6,7) = 1
Pair(6,1) = 0
Pair(6,2) = 0
Pair(6,3) = 0
Pair(6,4) = 0
Pair(7,1) = 0
Pair(7,2) = 0
Pair(7,3) = 0
Pair(7,4) = 0
Pair(7,5) = 0

Best Answer

C = {[1; 3; 5; 4; 6]; [1; 2; 3; 4; 5; 6; 7]; [1; 4; 3; 6]};
% generate list of all pairs from C elements
u = unique(cat(1,C{:}));
[v,w] = ndgrid(u);
allpairs = [w(:) v(:)];
% Get existing Pairs from C
cp = cellfun(@(a) [a(1:end-1) a(2:end)], C, 'unif', 0);
cp = cat(1,cp{:});
% Count
[b,J]=ismember(cp,allpairs,'rows');
n = accumarray(J(b),1,[size(allpairs,1),1]);
% Select top 5 (==p)
p = 5;
m = length(u);
[n,is] = sort(reshape(n,[m m]),1,'descend');
n = n(1:p,:);
toppairs = reshape(allpairs(is(1:p,:)+(0:m-1)*m,:),[],2);
count = n(:);
% Display
T = table(toppairs,count)