Matching values in different columns?

4 次查看(过去 30 天)
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 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by