How to stop finding a value once it has been attained? (Find function inside a loop)

6 ビュー (過去 30 日間)
SungJun Cho
SungJun Cho 2019 年 8 月 8 日
コメント済み: SungJun Cho 2019 年 8 月 9 日
Hello, I am finding a first nonzero value from the array within the while loop. However, the efficiency of my code got significantly lower as I tried to find a value from the entire array every time the code loops. Is there a way to stop finding a value once it has been found? Below is the excerpt of my code that is within the while loop.
ind_e = find(current_e(2,:),1,'first');
if exist('ind_e','var')
if k > ind_e
sur_current_e(1,k) = current_e(1,k-ind_e) - current_e(2,k);
end
end
Thank you very much.

回答 (2 件)

Brendan Collins
Brendan Collins 2019 年 8 月 8 日
SungJun,
You could try something like this. Set I to 0 outside of the loop somewhere than give it a shot.
ind_e = find(current_e(2,:),1,'first');
if I == 0
if exist('ind_e','var')
if k > ind_e
sur_current_e(1,k) = current_e(1,k-ind_e) - current_e(2,k);
I = 1;
end
end
end
This will check the variable I before running back through the loop for the rest of your while loop's iterations, but because you already found the number you want, I has been changed from 0 to 1, and the nested if will not run.
  1 件のコメント
SungJun Cho
SungJun Cho 2019 年 8 月 8 日
Thank you Brendan! Actually what I wanted was to somehow 'stop'
ind_e = find(current_e(2,:),1,'first');
this find command once I found the ind_e value. But thanks for your help.

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


Andrei Bobrov
Andrei Bobrov 2019 年 8 月 8 日
Please read about break in while loop.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by