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.

조회 수: 4 (최근 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 <.
  댓글 수: 2
sam  CP
sam CP 2018년 6월 25일
편집: sam CP 2018년 6월 25일
But i have to implement 8 conditions ...Not 3 conditions
Adam Danz
Adam Danz 2018년 6월 25일
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().

댓글을 달려면 로그인하십시오.

추가 답변 (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에서 Image Processing Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by