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

7 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by