How to write switch statement
Show older comments
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
Accepted Answer
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...
Categories
Find more on MATLAB Report Generator 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!

