필터 지우기
필터 지우기

Leave the whole for-loop

조회 수: 11 (최근 30일)
Anna
Anna 2013년 8월 30일
How can I leave the loop completely, if an "if" statement in that loop turns out to be true? I have tried break, but I guess that doesn't work in if-structures... My code structure looks like this:
for i = 1:5
(doing some stuff here)
if [something happens]
for [...], for [...], (assignments); end, end,
!and STOP COMPLETELY no further calculations are needed!
else
for [...], (assignments ); end
end
(doing more stuff)
end
Thanks for any help!

채택된 답변

Geert
Geert 2013년 8월 30일
편집: Geert 2013년 8월 30일
Why can't you use break? The break command can perfectly be used in combination with if statements. Break will execute the innermost for (or while) loop it is in...
Consider the following example:
for ii = 1:10
disp(['Current value of ii = ', num2str(ii)])
if ii>5
% execute some for loops
for kk=1:5
for ll=1:5
% put your commands here
end
end
% exit the for loop
break
else
for kk=1:5
% do something here
end
end
end
disp(['for loop was stopped at the moment that ii = ', num2str(ii)])
The break command will exit the innermost loop (type: help break):
break Terminate execution of WHILE or FOR loop.
break terminates the execution of FOR and WHILE loops.
In nested loops, break exits from the innermost loop only.
Does this clarifies it for you?
  댓글 수: 1
Simon
Simon 2013년 8월 30일
If you want to exit both loops from inside the innermost loop, try setting a bool variable before the loops
exitloop = false
Now you can set this variable to true in the inner loop and catch this in the outer loop like
if exitloop
break
end

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

추가 답변 (2개)

David Sanchez
David Sanchez 2013년 8월 30일
The break command exists the most inner for/while loop. For nested for loops, you have to set a flag so that when it is active, the whole loop finishes. Following you code structure, break should exit:
for i = 1:5
(doing some stuff here)
if [something happens]
for [...], for [...], (assignments); end, end,
!and STOP COMPLETELY no further calculations are needed!
break % this break here will cause to get out of the main for-loop since it is not place within another for-loop
else
for [...], (assignments ); end
end
(doing more stuff)
end

Anna
Anna 2013년 8월 30일
Thank you all for the excellent answers! You are totally right Geert, break works perfectly fine. I just had a different error in my code, and I had read something that threw me off when I googled my question, that's why I thought break doesn't work in if-structures. Everything works exactly as needed. Thanks again!

카테고리

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