Changing the number of iterations at runtime

조회 수: 25 (최근 30일)
mohammad
mohammad 2022년 12월 15일
댓글: Walter Roberson 2022년 12월 15일
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?

답변 (1개)

Walter Roberson
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
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by