Matching values in different columns?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Aragorn23
el 8 de Ag. de 2019
Comentada: Julian
el 4 de Oct. de 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.
0 comentarios
Respuesta aceptada
Adam Danz
el 8 de Ag. de 2019
Editada: Adam Danz
el 8 de Ag. de 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 comentarios
Julian
el 4 de Oct. de 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).
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!