Be the first to rate this file! 93 downloads (last 30 days) File Size: 3.68 KB File ID: #25162

stack

by Ben Petschel

 

28 Aug 2009

Code covered by BSD License  

manipulate stack objects as dynamic arrays

Download Now | Watch this File

File Information
Description

The stack object implemented here is a partial solution to the problem of dynamic arrays.

It is well known that appending elements to matlab arrays is inefficient (appending an element to a nx1 vector requires at least n assignments), e.g.

tic;v=[];for i=1:1e5,v=[v,i];end;toc; % O(n^2), approx 30 sec
tic;v=zeros(1e5,1); for i=1:numel(v),v(i)=i;end;toc; % O(n), approx 0.004 sec

In some applications we don't know the final length of the array. One solution is the use of stack objects.

A stack is a linked list containing the top item and a pointer to the top of the stack below. Here it is implemented as a nested cell array: s = {} (empty stack) or s = {x,s1} where s1 is a stack.

tic;
s={};
for i=1:1e5
  s=push(i,s);
end;
w=stack2mat(s,1e5);
isequal(v,w) % returns 1
toc; % approx 3 sec

The code for push and pop is rather trivial. The functions stack2mat and stack2cell are useful if you need to access elements of the stack other than the last.

NOTE: The reason this is called a "partial" solution to the problem of dynamic arrays:
1. the memory overhead seems to be 120 bytes per stack element (doubles use 8 bytes)
2. large stacks (e.g 1e6 elements) can cause matlab to terminate unexpectedly, which seems to be from a bug in the way matlab handles large nested cell arrays (only tested in R2009a).

MATLAB release MATLAB 7.8 (R2009a)
Zip File Content  
Other Files license.txt,
pop.m,
push.m,
stack2cell.m,
stack2mat.m
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
stack Ben Petschel 31 Aug 2009 14:47:59
dynamic array Ben Petschel 31 Aug 2009 14:48:00
use at own risk Ben Petschel 31 Aug 2009 14:48:00
 

MATLAB Central Terms of Use

NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Terms prior to use.

Contact us at files@mathworks.com