count of times if condition is met

73 views (last 30 days)
Tareq Khreim
Tareq Khreim on 21 Sep 2020
Commented: Tareq Khreim on 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 Comment
Stephen23
Stephen23 on 22 Sep 2020
Edited: Stephen23 on 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)

Sign in to comment.

Answers (2)

Jeff Miller
Jeff Miller on 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 on 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.

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!