repeating the loop until condition is met

Hello,
I have a prog, in which I have to repeat the function until a condition is met.
I used while loop, but it is running only once and coming out of the loop.
My code looks somewhat like this. It is a lengthy prog, hence just posting the gist.
iteration=0
while 1
calling a function which will give me an array
the returned array is checked to meet a specific requirement
if the requirement is not met, then call the function again.
iteration=iteration+1;
end

4 件のコメント

DGM
DGM 2021 年 4 月 23 日
I know what you wrote is just pseudocode, but it doesn't contain any exit condition. As given, it would be an infinite loop, which is contrary to what you describe. I'd need to know how you intend for the loop to exit.
If your while loop doesn't have an exit condition described in the first line (e.g. like this:)
% specify the exit condition normally
error=1;
while error>tol
% do stuff
error=abs(thing1-thing2);
end
Then it will have to break conditionally like this:
% or break out directly
while 1
% do stuff
if thinghappens
break;
end
end
Without knowing what the exit condition is and how it's satisfied, there's no way to answer this question with greater specificity. If it's exiting early, observe the value of the variables used to satisfy the exit condition and try to see if they are achieving their required values early or if the logical tests are incorrectly evaluating them.
NETHRAVATHI S
NETHRAVATHI S 2021 年 4 月 24 日
Thank you.
I got the solution. I did like this.
while 1
% do stuff
if thinghappens
break;
end
end
per isakson
per isakson 2021 年 4 月 24 日
編集済み: per isakson 2021 年 4 月 24 日
More standard
thinghappens = false;
while not( thinghappens )
% do stuff
end
DGM
DGM 2021 年 4 月 24 日
I can agree to that, but I was hoping that the obvious hint would be that the two can be combined.
while ~normalexitcondition
% do stuff
if abnormalexitcondition
warning('oh no!')
break;
end
end

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

回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2021 年 4 月 23 日

コメント済み:

DGM
2021 年 4 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by