MatLab As a Scripting Language
Peter Webb and Gregory V. Wilson 


Example 1: 

(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 the top of the stack. Return the 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 an element off the top of a stack. Return both stack and the 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 the contents of a stack object.
%   This function is called automatically to print the object when necessary
function display(s)
    disp('Stack object:');
    disp(['  ' num2str(s.top) ' elements']);
    for i=1:s.top
        disp(s.data{i});
    end
 ...


1


