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)
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?

Réponse acceptée

Jan
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()
n = 2
If the values are positive integers and smaller than 1000, this is slightly faster:
n = sum((x * [1000; 1]) == [2, 7] * [1000; 1])
n = 2
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
Elapsed time is 15.483181 seconds.
tic; for k = 1:r, n = sum(all(x == [2, 7], 2)); end, toc
Elapsed time is 0.219182 seconds.
tic; for k = 1:r, n = sum((x * [1000;1]) == 2007); end, toc
Elapsed time is 0.159192 seconds.
tic; for k = 1:r, n = sum(x(:, 1)==2 & x(:, 2)==7); end, toc
Elapsed time is 0.263742 seconds.
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
Elapsed time is 0.218550 seconds.

Plus de réponses (1)

Torsten
Torsten le 31 Oct 2022
Modifié(e) : Torsten le 31 Oct 2022
x_y_= [1 4; 5 3;9 8; 2 7;1 8;7 2; 2 7;1 5;4 3];
n = nnz(ismember(x_y_,[2,7],'rows'))
n = 2

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by