How to write switch statement
7 views (last 30 days)
Show older comments
Jordan Rosales
on 7 Feb 2021
Commented: Walter Roberson
on 8 Feb 2021
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
0 Comments
Accepted Answer
Cris LaPierre
on 8 Feb 2021
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 Comment
Walter Roberson
on 8 Feb 2021
"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)
fplot(f, [0 4])
But notice:
g(x) = 2 <= x < 3
does not do the same thing: it is only piecewise() that handles chained tests.
More Answers (1)
Walter Roberson
on 8 Feb 2021
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...
0 Comments
See Also
Categories
Find more on Install Products in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!