count of times if condition is met

83 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2020-9-22
编辑:Stephen23 2020-9-22
"...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)

请先登录,再进行评论。

回答(2 个)

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

Image Analyst
Image Analyst 2020-9-22
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.

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by