Changing the number of iterations at runtime
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Walter Roberson
2022-12-15
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 个评论
Walter Roberson
2022-12-15
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!