count of times if condition is met

67 ビュー (過去 30 日間)
Tareq Khreim
Tareq Khreim 2020 年 9 月 21 日
コメント済み: Tareq Khreim 2020 年 9 月 28 日
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
  1 件のコメント
Tareq Khreim
Tareq Khreim 2020 年 9 月 28 日
Thank you!

サインインしてコメントする。


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 Center および File ExchangeIntroduction 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