Switch Statements for detecting the sign of a number

6 views (last 30 days)
Hi, I want to detect the sign of a number that I entered with using switch statements
I wote the code there is a problem about returning the results
When I entered -1, the matlab returns: I do not know
Also When I entered 0, the matlab returns: The number is negative
Help me about this problem. This case could be easily done with using for loop but I want this with switch statements.
n=input('Enter a number ');
switch n
case n<0
disp('The number is negative')
case n==0
disp('The number is 0')
case n>0
disp('The number is positive')
otherwise
disp('I do not know')
end

Answers (2)

Walter Roberson
Walter Roberson on 14 Apr 2020
switch n case n<0 is effectively
if any(ismember(n, n<0))
n<0 is going to evaluate to either 0 or 1, and that is going to be compared to the number itself. Neither 0 nor 1 are less than 0, so n<0 will always be false (0), and ismember(0,0) is true so you would get a match.
If you must use logical tests in the case (not recommended because that is confusing to most people) then you need to use
switch true
  2 Comments
Std1
Std1 on 14 Apr 2020
Thank you very much, I am just learning Matlab and I want to try every functions on a problem. That is why I am using Switch statement.
DGM
DGM on 1 Oct 2024
Alternatively
switch sign(n)
case -1
disp('The number is negative')
case 0
disp('The number is 0')
case 1
disp('The number is positive')
otherwise
% this will occur for NaN
disp('n is not a number')
end

Sign in to comment.


Mitish
Mitish on 1 Oct 2024
n=input('enter the number')
switch true
case n<0
disp('negative number')
case n>0
disp('positive number')
case n==0
disp('zero')
otherwise
disp('other value')
end

Categories

Find more on Loops and Conditional Statements 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!