Exit from several, nested while or for loops with one command

120 views (last 30 days)
Hello Is there an easy way to quit nested while loops with a command?
For example:
while condition1 = true
...
while condition2 = true
...
while condition3 = true
...
if condition4 = true
leave all while loops and continue with 'command1';
end
end
end
end
command1;
I know that in nested loops, 'break' exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.

Accepted Answer

Jan
Jan on 14 Jan 2013
Edited: Jan on 14 Jan 2013
doRun = true;
while condition1 && doRun
...
while condition2 && doRun
...
while condition3 && doRun
...
if condition4 == true
leave all while loops and continue with 'command1';
doRun = false;
end
end
end
end
Command1;
Alternative:
% Call subfunction:
myLoops
command1;
...
function myLoops
while condition1 == true
...
while condition2 == true
...
while condition3 == true
...
if condition4 == true
return;
end
end
end
end
  4 Comments
Paul
Paul on 15 Jan 2013
Very interesting! I never knew that the effort for debugging grows exponentially with the number of GOTOs. I cannot find any informations on that in the internet(?) You have any link?
On this site, it is said, that GOTO can be useful for quitting nested loops, but should be used always with care: http://www.dotnettoad.com/index.php?/archives/20-when-not-to-use-the-goto-keyword.html
Jan
Jan on 15 Jan 2013
Edited: Jan on 15 Jan 2013
Another rule is, that professionally written software (educated and experienced programmers, bug control in a team work, unit tests, bug tracking, version control, costs > 1$ per line) contains about 1 bug per 1000 lines of code. Fixing a bug in a certain line affects three other lines also, which partially require further fixes afterwards.
Debugging a code seriously demands for a coverage report. A bunch of GOTOs increase the effort to find a valid set of inputs, which is appropriate to run each part of the code. The software for controlling the Tornado battle plane has been debugged to 99% only, while the last 1% has been performed during low-level flights over inhabitted areas in the densly settled middle Europe.
In consequence "GOTO should be used with care" means, that avoiding it is a good programming practice. Or in other words: When you avoid GOTO (and the rest of the axis of evil: EVAL and GLOBAL), you will find another way to implement bugs.
My favorite link about GOTO is:
Searching this forum will be helpful also:

Sign in to comment.

More Answers (1)

Apoorva Srivastava
Apoorva Srivastava on 14 Jun 2019
Edited: Apoorva Srivastava on 14 Jun 2019
If you want to stop the program completely but not close MATLAB, you can just use return. (Note: It can be used even without a function!)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!