MATLAB: Leave the whole for-loop

breakfor loopif statementloops

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!

Best Answer

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?