count of times if condition is met

73 vues (au cours des 30 derniers jours)
Tareq Khreim
Tareq Khreim le 21 Sep 2020
Commenté : Tareq Khreim le 28 Sep 2020
I have a simple if statement to count how many times certain values in a matrix are within a certain range. ptarget is a 100x3 matrix representing ijk vectors, in which I want to assess if the i and j componenets are within -0.5 and 0.5. If both are within this range, I count this. For some reason, the counting variable hits just stays at 1. How can I fix this?
N = 1e2 % Iterations
% ...
for i=1:N
hits = 0;
if ptarget(i,1)>=-0.5 && ptarget(i,1)<=0.5 && ptarget(i,2)>=-0.5 && ptarget(i,2)<=0.5
hits = hits + 1
end
end
  1 commentaire
Stephen23
Stephen23 le 22 Sep 2020
Modifié(e) : Stephen23 le 22 Sep 2020
"...I have a simple if statement to count how many times certain values in a matrix are within a certain range..."
Rather than unnecessary nested loops, the simpler MATLAB approach would be like this:
idx = ptarget(:,1)>=-0.5 && ptarget(:,1)<=0.5 && ptarget(:,2)>=-0.5 && ptarget(:,2)<=0.5
hits = nnz(idx)

Connectez-vous pour commenter.

Réponses (2)

Jeff Miller
Jeff Miller le 22 Sep 2020
put
hits = 0;
before the 'for' loop. You are resetting hits to 0 each time you check a new ptarget

Image Analyst
Image Analyst le 22 Sep 2020
Try this (no for loop needed):
rowsInRange = ptarget(:,1) >= -0.5 & ptarget(:,1) <= 0.5 & ptarget(:,2) >= -0.5 & ptarget(:,2) <= 0.5; % A logical vector.
hits = nnz(rowsInRange); % Count # of "true" values.

Catégories

En savoir plus sur Introduction to Installation and Licensing dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by