Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Function Name: ugaMath % Inputs (1): - (char) A string containing numbers and ma

ID: 3537269 • Letter: F

Question

Function Name: ugaMath

% Inputs (1): - (char) A string containing numbers and mathematical

% operators.

% Outputs (1): - (double) A number after performing the arithmetic

%

% Function Description:

% Write a function named "ugaMath" that takes in a string containing a

% arithemtic expression and returns the result as a type double from

% carrying out all indicated mathematical operations. The input will

% follow this format:

%   

% '<number><operator><number><operator><number>' and so on inside the

% string.

%

% <number> is replaced by a number, and <operator> is replaced by one of

% these five arithmetic operators: +, -, *, /, or ^. Since UGA ignores

% (or to be precise, forgets) the order of operations, the function

% should do the same.

%

% For example, the following expression is a problem stolen from UGA's

% MATH 4102 final exam. Supposed we have the string '5-2^3'. 5-2 would

% give 3, so 3^3 would give 27 as the final answer for the output.

%

% Notes:

% - The input string is guaranteed to start with a number. If the input

% contains only one number and nothing else, the function should return

% that number.

% - You may assume that the string does not contain negative numbers as

% operands, though the output may be negative.

% - The input would not contain an operator with no operands after it

% e.g. you will not be given '80+' as an input. Furthermore, the input

% would not contain any characters other than numbers and the five

% aforementioned operators.

%

% Hints:

% - The strtok() function may be useful.

% - While str2num() may seem like an easy solution, it will not give the

% correct answer for every case.

%

% Test Cases:

% num1 = ugaMath('20-35')

% num1 => -15

%

% num2 = ugaMath('11*37/82+3')

% num2 => 7.9634

%

% num3 = ugaMath('9.4')

% num3 => 9.4

%

% num4 = ugaMath('235^0/0.32*5.55-103.2+589.32/23.6^2.32*0.045+32-218')

% num4 => -131.4716

%

Explanation / Answer

format long;
function k = ugaMath(string)
delim = '+-*/^';
remain = string;
[token, remain] = strtok(remain,delim);
k = str2num(token);
while true
if isempty(remain) break; end
operator = remain(1);
[token, remain] = strtok(remain,delim);
switch operator
case '^'
k = (k^str2num(token));
case '/'
k = (k/str2num(token));
case '+'
k = (k+str2num(token));
case '-'
k = (k-str2num(token));
case '*'
k = (k*str2num(token));
end
end
end


disp('9.4')
ugaMath('9.4')
disp('235^0/0.32*5.55-103.2+589.32/23.6^2.32*0.045+32-218');
ugaMath('235^0/0.32*5.55-103.2+589.32/23.6^2.32*0.045+32-218')
disp('20-35');
ugaMath('20-35')
disp('11*37/82+3');
ugaMath('11*37/82+3')