Write a function that calculates the result of an arithmetic
Solution
Matlab function my_calculator_inverse_precedence.m for the problem
function [result] = my_calculator_inverse_precedence(expression)
stk_front = 0; % variable indicating the front of stack
st = \'\'; % empty stack
op_stk = []; % operator position monitor stack
op_pos = 0; % operator position stack front
N = length(expression);% length of the expression
for k = 1:N % loop to monitor each element in expression
% checking expression(k) is a operator or not
if(expression(k) == \'+\' || ...
expression(k) == \'-\' || ...
expression(k) == \'*\' || ...
expression(k) == \'/\' || ...
expression(k) == \'^\' )
if(op_pos == 0) % no operator loaded in stack
stk_front = stk_front+1;
st(stk_front) = expression(k);
op_pos = op_pos +1;
op_stk(op_pos) = stk_front;
else % stack have some operator
while( pre(st(op_stk(op_pos))) >= pre(expression(k))) % checking the precedence of operators
if(op_pos == 1) % one operator
C = num2str(str2num(st(1:stk_front))); % evaluating part of the expression
st(1:length(C)) = C; % updating stack with evaluated expression
stk_front = length(C);
op_pos = 0;
break;
else % Many operator
C = num2str(str2num(st(op_stk(op_pos-1)+1:stk_front)));% evaluating part of the expression
st(op_stk(op_pos-1)+1:op_stk(op_pos-1)+length(C)) = C; % updating stack with evaluated expression
stk_front = op_stk(op_pos-1)+length(C);
op_pos = op_pos-1;
end
end% adding new operotor in the stack
stk_front = stk_front+1;
st(stk_front) = num2str(expression(k));
op_pos = op_pos +1;
op_stk(op_pos) = stk_front;
end
% checking expression(k) is operand
else
% if yes add it in the stack
stk_front = stk_front+1;
st(stk_front) = num2str(expression(k));
end
end
% evaluating the expression
result = str2num(st(1:stk_front));
end
function val= pre(oper)
switch (oper)
case \'+\'
val = 2;
case \'-\'
val = 2;
case \'*\'
val = 1;
case \'/\'
val = 1;
case \'^\'
val = 0;
end
end
testing the function my_calculator_inverse_precedence.m
>> x = my_calculator_inverse_precedence(\'2*30+5^4\')
x =
24010000
>> (2*(30+5))^4
ans =
24010000
>> class(x)
ans =
double
>> x = my_calculator_inverse_precedence(\'4-3.14\')
x =
0.8600
>> x = my_calculator_inverse_precedence(\'4-2-2\')
x =
0
>>

