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
Samuel Katongole on 31 Mar 2020
Edited: Stephen23 on 31 Mar 2020
The script is here...
% Initiating the integer variable, num
% Prompting user to enter integer
num=input('Enter any integer value: ');
% Error check
if num<-10 || num>10
disp('OUT OF RANGE')
% 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
f4(num)% calculates the 5th power of num (esp. when num==4)
The output, for instance, looks like this...
>> switchnum
Enter any integer value: 5
ans =
which executes f4 instead of f1....why???

Answers (1)

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
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




Community Treasure Hunt

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

Start Hunting!