# I am trying to run this script, but it only returns the last part of the switch- the otherwise part, please help...

1 view (last 30 days)
Samuel Katongole on 31 Mar 2020
Edited: Stephen23 on 31 Mar 2020
The script is here...
% Initiating the integer variable, num
num=-10:10;
% Prompting user to enter integer
num=input('Enter any integer value: ');
% Error check
if num<-10 || num>10
disp('OUT OF RANGE')
end
% switching the num
switch num
case num<-2 || num>4;
f1(num)% calculates the square of num
case num>=0 && num<=2;
f2(num)% calculates the cube of num
case num==-2 || num==-1;
f3(num)% calculates the 4th power of num
otherwise
f4(num)% calculates the 5th power of num (esp. when num==4)
end
The output, for instance, looks like this...
>> switchnum
Enter any integer value: 5
ans =
3125
which executes f4 instead of f1....why???

Stephen23 on 31 Mar 2020
Edited: Stephen23 on 31 Mar 2020
Your switch condition will not work as you expect. If you want to use logical comparisons for the case values, then you will need to provide the appropriate true or false value for the switch condition, e.g.:
switch true % <- you need this!
case num<-2 || num>4
...
case num>=0 && num<=2
...
end
See other discussions on this topic:
Note that switch used in this way obfuscates the code, and is better written as a simple if statement:
if num<-2 || num>4
elseif num>=0 && num<=2
...
else
...
end

R2017b

### Community Treasure Hunt

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

Start Hunting!