Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Geoff Hayes
Geoff Hayes il 11 Feb 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.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by