How to Break 'switch' statement without exiting entire 'while' loop.
28 ビュー (過去 30 日間)
古いコメントを表示
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
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
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
2019 年 8 月 8 日
編集済み: Adam Danz
2019 年 8 月 16 日
Unlike other programming languages, "When a case expression is true, MATLAB executes the corresponding statements and exits the switch block."
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Argument Definitions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!