Matching values in different columns?

4 views (last 30 days)
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.

Accepted Answer

Adam Danz
Adam Danz on 8 Aug 2019
Edited: Adam Danz on 8 Aug 2019
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 Comments
Adam Danz
Adam Danz on 8 Aug 2019
Nice! I just learned about that function myself today!
Julian
Julian on 4 Oct 2019
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).

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!