Ask about break function

Hi, I am writing code to break out of loop. I have several loops, including nested loops. If I use break in a if command, it will jump out of all loops, or the very nearest loop(say only one loop)?
For example:
for i=1:10
for j=1:10
f(x)=...
if f(x)>10 ...
elseif f(x)<5 break;
....
end
end
end
If f(x)<5 for some i=2 and j=3; then break will jump out of loop, go to i=3, j=1 or i=2 j=4?
Thanks.

2 commentaires

Geoff
Geoff le 10 Juin 2012
In your last comment, I don't understand why you ask if (i,j) might go from (2,3) to (2,4) after a break with j as the inner loop. That would not be breaking at all. If you want that behaviour, use 'continue' to continue immediately from the next iteration. If you want to break out of BOTH loops from the inner loop, you need to set a flag, check it after the inner loop, and break again from there. Or use while-loops
C Zeng
C Zeng le 12 Juin 2012
Thank you, you are right! break make the loop of j ending, and start from a new i and j, right?
continue means do nothing in the loop and go to next loop?

Connectez-vous pour commenter.

 Réponse acceptée

Thomas
Thomas le 6 Juin 2012

1 vote

I think only the loop in which the break occurs is broken out of..
try
for ii=1:5
ii
for jj=1:6
jj
if ii==3 && jj==4
disp('broken here')
break;
end
end
end

5 commentaires

Walter Roberson
Walter Roberson le 6 Juin 2012
Yes, "break" and "continue" are only for the immediately containing loop.
C Zeng
C Zeng le 10 Juin 2012
Hi, it seems that after 'broken here' it go to (i,j)=(4,1), so it should break all loops.
Please double check it.
Thomas
Thomas le 12 Juin 2012
yes cos the break is the jj loop it will end count of jj and got to the next ii which is 4 and restartat jj which y it gets (ii,jj)=(4,1);
C Zeng
C Zeng le 12 Juin 2012
Oh, thanks! I got it.
Tomas
Tomas le 26 Mar 2013
if you wanted to break both fors this should work. adding a flag like geof said.
flag=0;
for ii=1:5
ii
if flag==1
break
end
for jj=1:6
jj
if ii==3 && jj==4
disp('broken here')
flag=1;
break;
end
end
end

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by