if i want to stop infinite while loop after 30 iteration, so how can i use it in my matlab code?
2 views (last 30 days)
Show older comments
if i want to stop infinite while loop after 30 iteration, so how can i use it in my matlab code?
0 Comments
Accepted Answer
Image Analyst
on 11 Feb 2013
Edited: Image Analyst
on 11 Feb 2013
loopCounter = 1
while true % Infinite loop
% Insert code here....
% At bottom of loop, break out of loop if counter = 30
if loopCounter >= 30
break;
end
% Done with code so now increment loop counter.
loopCounter = loopCounter + 1;
end
However I suggest that it's better to use a "for" loop than an infinite while loop that you have to break out of.
for k = 1:30
% Your code
end
Or you could have a non-infinite while loop where you test for the loopCounter on the "while" line, as you're normally expected to do. Any reason why you're not doing either of those methods?
More Answers (1)
Azzi Abdelmalek
on 11 Feb 2013
Edited: Azzi Abdelmalek
on 11 Feb 2013
test=0
while condition & test<=30
%your code
test=test+1
end
3 Comments
Image Analyst
on 11 Feb 2013
Edited: Image Analyst
on 11 Feb 2013
It's good to avoid infinite loops. You should always have a failsafe in there, like bail out if the number of iterations exceeds some number that you know is abnormally high, which means something went wrong. Otherwise it's possible for your program to hang the computer.
See Also
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!