-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheval_rpn.m
40 lines (34 loc) · 1.19 KB
/
eval_rpn.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function val = eval_rpn(expr)
stack = [];
for i = 1:length(expr)
current_element = expr{i};
% push numeric digits onto stack.
if ( isnumeric(current_element) )
stack = [ stack, current_element ];
else
% pop operands from stack (only considering binary ops).
operands = stack( (end-1):end );
stack = stack(1:(end-2));
% evaluate
switch (current_element)
case '+'
result = operands(1) + operands(2);
case 'x'
result = operands(1) * operands(2);
% overload.
case '*'
result = operands(1) * operands(2);
case '-'
result = operands(1) - operands(2);
case '/'
result = operands(1) / operands(2);
otherwise
error('Unknown operator %c', expr(i));
end
% push back onto stack
stack = [stack, result];
end
end
% This should work.
val = stack(1);
end