Dr. Dobb's Journal January 1999
(a)
% STACK Create an empty stack object
% Constructor for a simple stack class using a cell-array.
function s = stack()
s.data = {}; % Make an empty cell-array
s.top = 0; % Nothing in the stack yet
s = class(s, 'stack'); % Turn the structure into a class object
...
(b)
% PUSH Add an element to top of stack. Return new stack.
function s = push(s,x)
s.top = s.top + 1; % Increment the top index
s.data{s.top} = x; % Add the element to the stack
...
(c)
% POP Pop element off top of stack. Return both stack and element.
function [s, e] = pop(s, x)
if (s.top == 0), error('Cannot pop() empty stack'), end
e = s.data{s.top};
s.top = s.top - 1;
...
(d)
% DISPLAY Print contents of a stack object.
% Called automatically to print object when necessary
function display(s)
disp('Stack object:');
disp([' ' num2str(s.top) ' elements']);
for i=1:s.top
disp(s.data{i});
end
...