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

1 visualización (últimos 30 días)
Alexander Nicholas
Alexander Nicholas el 10 de Abr. de 2017
Respondida: Guillaume el 10 de Abr. de 2017
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)

Respuestas (2)

Adam
Adam el 10 de Abr. de 2017
Editada: Adam el 10 de Abr. de 2017
case(op=='+')
is not valid. Use
case('+')
instead
  3 comentarios
Thorsten
Thorsten el 10 de Abr. de 2017
BTW: You don't need the parentheses around '+'.

Iniciar sesión para comentar.


Guillaume
Guillaume el 10 de Abr. de 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

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by