Filter löschen
Filter löschen

Changing the number of iterations at runtime

3 Ansichten (letzte 30 Tage)
mohammad
mohammad am 15 Dez. 2022
Kommentiert: Walter Roberson am 15 Dez. 2022
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?

Antworten (1)

Walter Roberson
Walter Roberson am 15 Dez. 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 Kommentar
Walter Roberson
Walter Roberson am 15 Dez. 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

Melden Sie sich an, um zu kommentieren.

Kategorien

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

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by