Switch not recognizing that 0 is greater than -1
2 views (last 30 days)
Show older comments
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 Comments
per isakson
on 21 Oct 2019
Edited: per isakson
on 21 Oct 2019
Read the documentation on switch
Your code make me think you should rather use if, elseif, else, end
KALYAN ACHARJYA
on 21 Oct 2019
Edited: KALYAN ACHARJYA
on 21 Oct 2019
Yes it should be , when x=0, then case 1
Again it's easy with if else, as mentioned by @Per Isakson
Answers (2)
the cyclist
on 21 Oct 2019
Edited: the cyclist
on 21 Oct 2019
"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 Comment
Walter Roberson
on 18 Jul 2023
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
on 18 Jul 2023
x = 0;
switch true
case x<-1
y=1
case x<=2
y=x^2
otherwise
y=4
end
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!