Force a while loop to stop after a set number of iterarions?

8 views (last 30 days)
I have set a loop that only stops when a certain condition is achieved, taking into account variables from another script. Please keep in mind that this loop is several hundreds of lines long.
while not(Condition)
Loop
end
However, not all situations will result in the condition being achieved. It will just loop ad infinitum.
Due to this, I'm trying to set a rule where if the condition is not achieved after 5000 iterations of the loop, the loop is forced to stop. How could I set this?
Thank you in advance for all help.
  1 Comment
Miriam
Miriam on 9 Oct 2018
https://www.mathworks.com/matlabcentral/answers/63052-if-i-want-to-stop-infinite-while-loop-after-30-iteration-so-how-can-i-use-it-in-my-matlab-code

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 9 Oct 2018
Edited: Guillaume on 9 Oct 2018
counter = 0;
maxiterations = 5000;
while ~condition && counter < maxiterations
counter = counter + 1;
%... rest of code
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!