how can ı write opposite of while loop

so i wanted to write loop but my loop need to be opposite of while loop,i mean you know when condition is true while loop keep doing loop and when condition is wrong, loop stop and continue to code. So my loop need to stop when condition is true and my loop need to continue to looping when my condition is wrong.

답변 (1개)

Chad Greene
Chad Greene 2018년 8월 18일

0 개 추천

Just add a ~ to whatever statement you're using for the while loop. So instead of
while a==b
...
end
You could do
while ~(a==b)
...
end

댓글 수: 2

It would not be uncommon to want to stop a loop as soon as it was detected that the condition was true. For that you could use
while true
.... some code ...
if condition_goes_here
break;
end
... more code ...
end
I'd add a failsafe of the max allowable iterations to be extra robust and prevent infinite loops:
maxIterations = 1000000; % Whatever you think will be way more than you would expect.
loopCounter = 1;
while loopCounter < maxIterations
.... some code ...
if condition_goes_here
break;
end
... more code ...
loopCounter = loopCounter + 1;
end

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

mts
2018년 8월 18일

댓글:

2018년 8월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by