How to write switch statement
显示 更早的评论
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
采纳的回答
更多回答(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...
类别
在 帮助中心 和 File Exchange 中查找有关 MATLAB Report Generator 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


