How to write switch statement

10 ビュー (過去 30 日間)
Jordan Rosales 2021 年 2 月 7 日
コメント済み: Walter Roberson 2021 年 2 月 8 日
For an assignment i am supposed to convert this if else statement into a switch case statement:
if val > 5
if val < 7
disp('ok(val)')
elseif val < 9
disp('xx(val)')
else
disp('yy(val)')
end
else
if val < 3
disp('yy(val)')
elseif val == 3
disp('tt(val)')
else
disp('mid(val)')
end
end
Currently I have this, however it does not display anything when assign val any number, except 1:
switch val
case val < 3
disp('yy(val)')
case val == 3
disp('tt(val)')
case 3 < val <= 5
disp('mid(val)')
case 5 < val < 7
disp('ok(val)')
case 7 <= val < 9
disp('xx(val)')
case 9 < val
disp('yy(val)')
end

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

採用された回答

Cris LaPierre 2021 年 2 月 8 日
Your syntax for the logical comparison is incorrect. You can't perform 2 comparisons on the same item. You must split this into 2 conditional statements.
% incorrect
case 3 < val <= 5
% Correct
case 3 < val && val <= 5
The next thing to realize is that a switch statement looks for the case that matches the value you are switching on. This means your switch val has to match an actual value listed in a case statement. You case statements all perform logical comparicsons, so their value is true or false (1 or 0). If val is ever anything other than 1, it can't find a match.
You are looking for the true case, so use switch true.
1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Walter Roberson 2021 年 2 月 8 日
"You can't perform 2 comparisons on the same item" is not completely correct, with the exception being in the processing of piecewise() involving symbolic expressions.
syms x
f(x) = piecewise(x < 2, 1, 2 <= x < 3, 2, 3)
f(x) =
fplot(f, [0 4])
But notice:
g(x) = 2 <= x < 3
g(x) =
does not do the same thing: it is only piecewise() that handles chained tests.

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

その他の回答 (1 件)

Walter Roberson 2021 年 2 月 8 日
You can use the obscure
switch true
However you will need to fix your chains of conditions. In MATLAB,
3 < val <= 5
is
((3 < val) <= 5)
The first part is evaluated and returns 0 (false) or 1 (true), and you then compare the 0 or 1 to 5...

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by