I got a value followed by a program, I want to print some message by using switch statement. I wrote some code , but wrong case is working.

1 次查看(过去 30 天)
If my result is between 22 and 34 then i have to print "red", result is between 34 and 67 then message should "green", otherwise "blue". I wrote following code.When my result=27 then it will print 'blue', it will always print 'blue. I knew that this will always work on 'otherwise'. How can i solve this?
if true
switch (n)
case (22<n)&&(n<33)
disp('red')
case (33<n)&&(n<67)
disp('green')
otherwise
disp('blue')
end
end

采纳的回答

Adam Danz
Adam Danz 2018-6-25
编辑:Adam Danz 2018-6-25
It looks like you're mixing up switch/case and logical conditionals. Each case in your example should be a possible outcome of 'n'. If n=23, when you evaluate your first case, (22<n)&&(n<33) = true (=1). But the switch/case is looking for 23. Since none of your cases match 23, it always ends up in 'otherwise'.
In your example, get rid of the switch/case and replace it with conditionals.
if (22<n)&&(n<33)
disp('red')
elseif(33<n)&&(n<67)
disp('green')
else
disp('blue')
end
If n could equal 22, 33, or 67 you might want to use <= rather than <.

更多回答(1 个)

Guillaume
Guillaume 2018-6-25
You are inventing your own syntax for switch, it's no wonder it doesn't work.
While there is a way to make your tests work with switch it would be a very obscure syntax that would confuse many people. So I would recommend not to use it. Instead use if ... elseif ...:
if n >= 22 & n < 33
disp('red');
elseif n >= 33 & n < 67
disp('green');
elseif n >= 67 & n < 100
disp('blue');
else
disp('purple');
end
Notice that I have changed some of the comparisons to >= as in your original code, if n was exactly equal to an edge value, it would never match anything.
However, your case attempt and the above is a lot of work which can be easily replaced by just two lines using discretize
outputs = {'', 'red', 'green', 'blue', 'purple'}; %the '' is for values less than 22
disp(outputs{discretize(n, [-Inf, 22, 33, 67, 100, Inf])});
It's also trivial to add new outputs/thresholds with this.
Now, if you really really want to use switch:
%WARNING: OBSCURE SYNTAX. DO NOT USE
switch true
case n >= 22 & n < 33
disp('red');
case n >= 33 & n < 67
disp('green');
case n >= 67 & n < 100
disp('blue');
otherwise
disp('purple');
end

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by