count of times if condition is met

67 visualizaciones (últimos 30 días)
Tareq Khreim
Tareq Khreim el 21 de Sept. de 2020
Comentada: Tareq Khreim el 28 de Sept. de 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 comentario
Stephen23
Stephen23 el 22 de Sept. de 2020
Editada: Stephen23 el 22 de Sept. de 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)

Iniciar sesión para comentar.

Respuestas (2)

Jeff Miller
Jeff Miller el 22 de Sept. de 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 el 22 de Sept. de 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.

Categorías

Más información sobre Introduction to Installation and Licensing en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by