Switch not recognizing that 0 is greater than -1

조회 수: 2 (최근 30일)
Jacob Herbster
Jacob Herbster 2019년 10월 21일
댓글: Walter Roberson 2023년 7월 18일
This always provides an outcome of 1 when plugging 0 for x, when it should be 0^2 or 0
switch x
case x<-1
y=1
case x<=2
y=x^2
otherwise
y=4
end
y =
1
  댓글 수: 2
per isakson
per isakson 2019년 10월 21일
편집: per isakson 2019년 10월 21일
Read the documentation on switch
Your code make me think you should rather use if, elseif, else, end
KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 10월 21일
편집: KALYAN ACHARJYA 2019년 10월 21일
Yes it should be , when x=0, then case 1
Again it's easy with if else, as mentioned by @Per Isakson

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

답변 (2개)

the cyclist
the cyclist 2019년 10월 21일
편집: the cyclist 2019년 10월 21일
Quoting the Tips section of the documentation for switch:
"A case_expression cannot include relational operators such as < or > for comparison against the switch_expression. To test for inequality, use if, elseif, else statements."
Your case_expression is x<-1, which violates that.
  댓글 수: 1
Walter Roberson
Walter Roberson 2023년 7월 18일
More accurate is that it is not recommended that case_expression includes relational operators. Whatever the result is of the case expression (even if that is true or false) is going to be compared to the switch value.

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


Stephen23
Stephen23 2023년 7월 18일
x = 0;
switch true
case x<-1
y=1
case x<=2
y=x^2
otherwise
y=4
end
y = 0

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by