How to use switch to choose and operator within a function?

3 views (last 30 days)
Having issues relying on switch to decide an operator within a function. I know using if, else statements would be easier but using switch is part of the assignment. How can I fix this function in order to make it work properly?
---function---
function r=calc_switch(a,b)
op=input('Input Operator: ');
switch(op)
case(op=='+')
r=a+b;
case(op=='-')
r=a-b;
case(op=='*')
r=a*b;
case(op=='/')
r=a/b;
end
fprintf('The value r is: %d\n',r)
---command window---
>> calc_switch(5,5)
Input Operator: '/'
Undefined function or variable 'r'.
Error in calc_switch (line 13)
fprintf('The value r is: %d\n',r)

Answers (2)

Adam
Adam on 10 Apr 2017
Edited: Adam on 10 Apr 2017
case(op=='+')
is not valid. Use
case('+')
instead

Guillaume
Guillaume on 10 Apr 2017
As Adam said, your case syntax is not valid.
The reason you got the error Undefined function or variable 'r'. is because none of your case applied, therefore r never got created.
As it's very easy for the user to enter a wrong input, you really ought to respond to that case rather than let your script error with an obscure message. So this should tell you to add an otherwise option to your switch:
switch op
case ...
...
case ...
...
otherwise
error('Could not recognise operator: %s', op);
end
Note, however, that the whole thing could be written without switch, using look-up tables instead:
function r=calc_switch(a, b)
operators = '+-*/';
opfuns = {@plus, @minus, @mtimes, @mrdivide}; %actual function to invoke, in the same order as operators . Note that you may prefer @times and @rdivide to perform memberwise multiplication and division
op = input('Input Operator: ');
[valid, opidx] = ismember(op, operators);
if ~valid
error('Could not recognise operator: %s', op);
end
r = opfun{opidx}(a, b);
end

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!