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

28 ビュー (過去 30 日間)
Alexander Thew
Alexander Thew 2019 年 8 月 8 日
編集済み: Adam Danz 2019 年 8 月 16 日
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 件のコメント
Bruno Luong
Bruno Luong 2019 年 8 月 8 日
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 2019 年 8 月 8 日
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.

サインインしてコメントする。

回答 (1 件)

Adam Danz
Adam Danz 2019 年 8 月 8 日
編集済み: Adam Danz 2019 年 8 月 16 日
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

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by