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

2 次查看(过去 30 天)
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 个评论
Md Shahidullah Kawsar
@Image Analyst for this cell array C = {[1; 3; 5; 4; 6]; [1; 2; 3; 4; 5; 6; 7]; [1; 4; 3; 6]}; total 13 pairs are possible.
1 3
3 5
5 4
4 6
1 2
2 3
3 4
4 5
5 6
6 7
1 4
4 3
3 6

请先登录,再进行评论。

采纳的回答

Bruno Luong
Bruno Luong 2018-11-7
编辑:Bruno Luong 2018-11-7
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)

更多回答(1 个)

Stephen23
Stephen23 2018-11-7
编辑:Stephen23 2018-11-7
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.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by