Matching values in different columns?

조회 수: 5 (최근 30일)
Aragorn23
Aragorn23 2019년 8월 8일
댓글: Julian 2019년 10월 4일
Hi everyone,
I have a matrix with two columns of data. The data in the first column vary from 1 to 120. The data in the second column vary from 1 to 12.
A= [10 13 10 1 111 102 10 13 7 10 112 100 14 116 102 10 14 120].
B= [2 4 5 7 12 1 2 6 7 9 12 2 4 7 9 11 12 12].
I would like to calculate the number of times each element of column A matches with different elements of column B. For example, the number 10 matches two times with 2, and one time with 5, 9 and 11.
How can I do that?
Thanks.

채택된 답변

Adam Danz
Adam Danz 2019년 8월 8일
편집: Adam Danz 2019년 8월 8일
If you have r2019a, use groupcounts().
%Original data
A= [10 13 10 1 111 102 10 13 7 10 112 100 14 116 102 10 14 120];
B= [2 4 5 7 12 1 2 6 7 9 12 2 4 7 9 11 12 12];
% Put data into a table
T = table(A.', B.','VariableNames',{'A','B'});
matchTable = groupcounts(T,{'A','B'}); % summary table
Result
matchTable =
17×3 table
A B GroupCount
___ __ __________
1 7 1
7 7 1
10 2 2
10 5 1
10 9 1
10 11 1
13 4 1
13 6 1
14 4 1
14 12 1
100 2 1
102 1 1
102 9 1
111 12 1
112 12 1
116 7 1
120 12 1
If your version of matlab is prior to r2019a
You can use unique() and histcounts() to get the same result as above.
%Original data
A= [10 13 10 1 111 102 10 13 7 10 112 100 14 116 102 10 14 120];
B= [2 4 5 7 12 1 2 6 7 9 12 2 4 7 9 11 12 12];
[sorted, ~, groups] = unique(sortrows([A.',B.']),'rows','stable');
counts = histcounts(categorical(groups),categorical(unique(groups,'stable')));
matchTable = array2table([sorted,counts.'],'VariableNames',{'A','B','Count'}); % summary table
  댓글 수: 3
Adam Danz
Adam Danz 2019년 8월 8일
Nice! I just learned about that function myself today!
Julian
Julian 2019년 10월 4일
BTW, you can get exactly the same answer with groupsummary
groupsummary(T,{'A','B'}); % summary table
that was introduced 1 year before groupcounts (since R2018a).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by