Changing the number of iterations at runtime
8 views (last 30 days)
Show older comments
I ran MATLAB with 1000 iterations, now it has reached the 500th iteration and I want it to be the last iteration. Is this possible while running the code?
0 Comments
Answers (1)
Walter Roberson
on 15 Dec 2022
I suspect you are talking about for loops.
The answer for those is that that cannot be done.
You can modify the loop index, but as soon as the next iteration starts, MATLAB will overwrite with the next value of the variable. The current iteration value is effectively held in a hidden variable, so changes to the loop control variable do not affect the looping.
You can put in a breakpoint, but once stopped, you cannot use "break" or "continue" or "return". You can dbquit but if you do then execution will stop without executing any further lines of code.
If you have a situation where you expect that you might want to break early, then you should code in the possibility, such as
break_early = false;
for K = 1 : 1000
stuff here
if break_early; break; end
end
Then if you breakpoint in the loop, you can set the variable break_early to true and the loop will terminate the next time the test is reached.
1 Comment
Walter Roberson
on 15 Dec 2022
Another approach to consider is to use a try/catch and generate an error at the breakpoint. Something like
try
for K = 1 : 1000
stuff here
end
catch ME
%user stopped early
end
stuff after loop
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!