Matching values in different columns?

5 Ansichten (letzte 30 Tage)
Aragorn23
Aragorn23 am 8 Aug. 2019
Kommentiert: Julian am 4 Okt. 2019
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.

Akzeptierte Antwort

Adam Danz
Adam Danz am 8 Aug. 2019
Bearbeitet: Adam Danz am 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 Kommentare
Adam Danz
Adam Danz am 8 Aug. 2019
Nice! I just learned about that function myself today!
Julian
Julian am 4 Okt. 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).

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by