How to Break 'switch' statement without exiting entire 'while' loop.

21 Ansichten (letzte 30 Tage)
Alexander Thew
Alexander Thew am 8 Aug. 2019
Bearbeitet: Adam Danz am 16 Aug. 2019
I have a piece of code with the following structure
while x < y
switch z
case z=1
if condition = true
break
end
end
end
I want the 'break' command to only exit the switch case, with the code progressing by iterating the 'while' loop but in this case it is breaking all the way out and entering the next section of code which is producing some plots. The documentation says the 'break' command should jump to the next 'end' in the code but clearly this is not happening. What's going wrong?
  3 Kommentare
Bruno Luong
Bruno Luong am 8 Aug. 2019
case z=1
This is not correct case syntax.
There is nothing to be break in a switch, since it does not loop. If you don't want to carry out some code in some case, just use a normal IF statement with appropriate test.
Adam Danz
Adam Danz am 8 Aug. 2019
Yeah, that would evoke an error, "Incorrect use of '=' operator". I'm assuming it should be "case 1" and that this is a simplified example.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Adam Danz
Adam Danz am 8 Aug. 2019
Bearbeitet: Adam Danz am 16 Aug. 2019
Once the case that equals 'Z' is entered, all other case are ignored. So there's no need to insert a break. Just remove the break.
[Update]
If your intentions are to skip everything else in the while-loop following that condition, you need to use continue, not break.
% assuming this is a simplified example....
while x < y
switch z
case 1
if condition = true
continue % <----- skip to next iteration of while-loop
end
end
end

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by