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

28 visualizaciones (últimos 30 días)
Alexander Thew
Alexander Thew el 8 de Ag. de 2019
Editada: Adam Danz el 16 de Ag. de 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 comentarios
Bruno Luong
Bruno Luong el 8 de Ag. de 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 el 8 de Ag. de 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.

Iniciar sesión para comentar.

Respuestas (1)

Adam Danz
Adam Danz el 8 de Ag. de 2019
Editada: Adam Danz el 16 de Ag. de 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

Categorías

Más información sobre Argument Definitions en Help Center y File Exchange.

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by