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 view (last 30 days)
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

Accepted Answer

Adam Danz
Adam Danz on 25 Jun 2018
Edited: Adam Danz on 25 Jun 2018
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 <.
  2 Comments
Adam Danz
Adam Danz on 25 Jun 2018
The if/then example consumes the same number of lines as a switch/case syntax would. The simplest form would be to use @Guillaume's example which uses discretize().

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 25 Jun 2018
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

Community Treasure Hunt

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

Start Hunting!

Translated by