Effacer les filtres
Effacer les filtres

Not quite sure what I'm doing wrong for this calculator function problem

2 vues (au cours des 30 derniers jours)
I have a project where I need to make a calculator that takes two input numbers and performs the operation (chosen by the user) on those numbers. I'm not sure what is going wrong with my code but when I tried calling the function like this:
result = kno20Calculator (5, 10, 'add')
I get the error message, "Matrix dimensions must agree". Also im aware there will probably be an issue with the log operation but I'll get around to that later. Here is my code:
function [result] = kno20Calculator(num1, num2, indicator) %#ok<*INUSD>
indicator = 'add'|'subtract'|'multiply'|'divide'|'exponent'|'lognum2(num1)'|'max'|'min';
if indicator == 'add'
result = num1 + num2;
elseif indicator == 'subtract'
result = num1 - num2;
elseif indicator == 'multiply'
result = num1 * num2;
elseif indicator == 'divide'
result = num1/num2;
elseif indicator == 'exponent'
result = num1^num2;
elseif indicator == 'lognum2(num1)'
result = lognum2(num1);
elseif indicator == 'max'
result = max(num1, num2);
elseif indicator == 'min'
result = min(num1, num2);
end
Thanks

Réponse acceptée

Geoff Hayes
Geoff Hayes le 11 Fév 2018
Kristen - when comparing strings, please use strcmp as you will get the error that you describe when you try to use the equality operator on two different sized character arrays. For example,
'hello' == 'goodbye'
generates the error.
Replace the == comparisons with
if strcmp(indicator,'add')
% do something
elseif strcmp(indicator,'subtract')
% etc.
endif
Do this for all of your conditions. Also, remove the second line of the function that seems to reinitialize the input parameter indicator to a string of all possible values.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by