How to count the top five pairs (for each digit) which have the highest number of occurrences in a cell array?
3 views (last 30 days)
Show older comments
Md Shahidullah Kawsar
on 7 Nov 2018
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
4 Comments
Accepted Answer
Bruno Luong
on 7 Nov 2018
Edited: Bruno Luong
on 7 Nov 2018
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)
2 Comments
More Answers (1)
Stephen23
on 7 Nov 2018
Edited: Stephen23
on 7 Nov 2018
Simpler:
>> C = {[1;3;5;4;6]; [1;2;3;4;5;6;7]; [1;4;3;6]};
>> H = cellfun(@(v)hankel(v(1:end-1),v(end-1:end)),C,'uni',0);
>> H = vertcat(H{:})
>> P = accumarray(H,1)
P =
0 1 1 1 0 0 0
0 0 1 0 0 0 0
0 0 0 1 1 1 0
0 0 1 0 1 1 0
0 0 0 1 0 1 0
0 0 0 0 0 0 1
For example:
P(1,2)=1
P(1,3)=1
P(1,4)=1
P(2,3)=1
... etc.
0 Comments
See Also
Categories
Find more on Logical 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!