필터 지우기
필터 지우기

How to write switch statement

조회 수: 13 (최근 30일)
Jordan Rosales
Jordan Rosales 2021년 2월 7일
댓글: Walter Roberson 2021년 2월 8일
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

채택된 답변

Cris LaPierre
Cris LaPierre 2021년 2월 8일
Your syntax for the logical comparison is incorrect. You can't perform 2 comparisons on the same item. You must split this into 2 conditional statements.
% incorrect
case 3 < val <= 5
% Correct
case 3 < val && val <= 5
The next thing to realize is that a switch statement looks for the case that matches the value you are switching on. This means your switch val has to match an actual value listed in a case statement. You case statements all perform logical comparicsons, so their value is true or false (1 or 0). If val is ever anything other than 1, it can't find a match.
You are looking for the true case, so use switch true.
  댓글 수: 1
Walter Roberson
Walter Roberson 2021년 2월 8일
"You can't perform 2 comparisons on the same item" is not completely correct, with the exception being in the processing of piecewise() involving symbolic expressions.
syms x
f(x) = piecewise(x < 2, 1, 2 <= x < 3, 2, 3)
f(x) = 
fplot(f, [0 4])
But notice:
g(x) = 2 <= x < 3
g(x) = 
does not do the same thing: it is only piecewise() that handles chained tests.

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

추가 답변 (1개)

Walter Roberson
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...

카테고리

Help CenterFile Exchange에서 Assumptions에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by