% Function Name: ugaMath % Inputs (1): - (char) A string containing numbers and
ID: 3537368 • Letter: #
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
function y = ugaMath(s)
s = regexprep(s,'[0-9]*.?[0-9]+',' $0 ');
v = regexp(s,' ','split');
l=length(v);
res=eval(v{2});
i=2;
while(i < (l-1) )
res=eval(strcat(num2str(res),v{i+1},v{i+2}));
i=i+2;
end
y=res;
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.