Consider the following code. (a) What do the functions push and pop really do? (b) What is the result of the code that follows the function definitions? (c) Why is it safe to make s a simple array instead of a cell array? (d) Why are there sprintf functions in the eval line? function s = push(v, s) s = [v s]: end function [v s] = pop(s) v = s(1): s = s(2: end): end x = {5, 14, 2, ‘*’, 6, ‘+’, ‘-‘, 3, ‘+’} stack = __: for ii = 1: length(x) if isnumeric(x{ii}) stack = push(x(ii), stack) elseif ismember (x (ii), stack) elseif ismember(x(ii), ‘+*-/’ [a stack] = pop (stack): [b stack] = pop (stack): c = eval ([sprintf (a) x(ii) sprintf (b)]): stack = push(c, stack): end end [v stack] = pop(stack): disp(v)
Expert Answer
a) The push function pushes the element v (operand or operator) of the array onto top of stack s and pop function pops out the top element of the stack s.
b) The result = -26
5 14 2
* is applied to top two elements
5 28
5 28 6
+ is applied on 28 and 6
5 34
– is applied on 5 and 34, 5-34 = -29
-29 3
+ is applied on -29 and 3
result = -26
c)
Simple array can easily implement stack
d)
sprintf function result in values of top two elements of stack s , ie a and b operands on which operator xii is applied by using eval.
eg eval(14 * 2) = 28