How would I use the 'count' function but to only count instances of both columns being specified?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
If I have a matrix of 2 columns with independant data in them, how would I count the number of instances of a specific combination occuring. For examples if the matrix is 2 columns of integers from 1-10
x_y_= [1 4; 5 3;9 8; 2 7;1 8;7 2; 2 7;1 5;4 3]
how would I count the number of lines that read as 2,7 (but not 7,2) for example?
0 commentaires
Réponse acceptée
Jan
le 31 Oct 2022
Modifié(e) : Jan
le 17 Déc 2022
x = [1 4; 5 3;9 8; 2 7;1 8;7 2; 2 7;1 5;4 3];
n = sum(all(x == [2, 7], 2)) % Alternative: nnz() instead of sum()
If the values are positive integers and smaller than 1000, this is slightly faster:
n = sum((x * [1000; 1]) == [2, 7] * [1000; 1])
A speed comparison:
x = randi([1, 100], 1e6, 2);
r = 100; % Repeat to reduce noise
tic; for k = 1:r, n = nnz(ismember(x,[2,7],'rows')); end, toc
tic; for k = 1:r, n = sum(all(x == [2, 7], 2)); end, toc
tic; for k = 1:r, n = sum((x * [1000;1]) == 2007); end, toc
tic; for k = 1:r, n = sum(x(:, 1)==2 & x(:, 2)==7); end, toc
tic; for k = 1:r % And a dull not matlabish loop:
n = 0; for i=1:size(x, 1), if x(i,1)==2 & x(i,2)==7, n=n+1; end, end
end, toc
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!