Code covered by the BSD License  

Highlights from
stack

from stack by Ben Petschel
manipulate stack objects as dynamic arrays

v=stack2cell(s,n)
function v=stack2cell(s,n)
% stack/stack2mat: converts a stack to a cell
% usage: v=stack2cell(s)
%        v=stack2cell(s,n)
%
% s is either an empty cell array or of the form {x,s1} where s1 is a stack
%
% stack2cell(s,n) puts all the elements of s into a nx1 cell array and
% gives a warning if the number of elements in the stack is not n.
% stack2cell(s) determines n automatically but is about 2x slower to run,
% as it requires an additional pass through the stack.
%
% Example: create (1:n)', using a stack:
%   s={};
%   n=1e5;
%   for i=1:n
%     s=push(i,s);
%   end;
%   v = stack2cell(s);
%   isequal(v,num2cell((1:n)'))  % should be 1
%
% See also: push, pop, stack2mat

% Author: Ben Petschel 28/8/2009
% Version history:
%   28/8/2009 - first release

if nargin==2
  % length of stack is given
  v = cell(n,1);
  while n>0 && ~isempty(s)
    % keep popping until stack is empty or cell is filled
    [x,s]=pop(s);
    v{n}=x;
    n=n-1;
  end;
  if n>0 || ~isempty(s)
    % stack emptied before cell filled, or vice-versa
    warning('stack:stack2cell:stacksize','actual and provided stack sizes do not agree');
  end;
else
  % have to determine the length (height) of the stack
  t=s;
  n=0;
  % find the depth of s
  while ~isempty(t)
    [x,t]=pop(t);
    n=n+1;
  end;
  % now put all the x in a cell array
  v=cell(n,1);
  while ~isempty(s)
    [x,s]=pop(s);
    v{n}=x;
    n=n-1;
  end;
end;

end

Contact us at files@mathworks.com