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 Kommentare

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.
Thank you.
I got the solution. I did like this.
while 1
% do stuff
if thinghappens
break;
end
end
per isakson
per isakson am 24 Apr. 2021
Bearbeitet: per isakson am 24 Apr. 2021
More standard
thinghappens = false;
while not( thinghappens )
% do stuff
end
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

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 23 Apr. 2021

Kommentiert:

DGM
am 24 Apr. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by