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

28 vues (au cours des 30 derniers jours)
Alexander Thew
Alexander Thew le 8 Août 2019
Modifié(e) : Adam Danz le 16 Août 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 commentaires
Bruno Luong
Bruno Luong le 8 Août 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 le 8 Août 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.

Connectez-vous pour commenter.

Réponses (1)

Adam Danz
Adam Danz le 8 Août 2019
Modifié(e) : Adam Danz le 16 Août 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

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by