Desta Haileselassie Hagos
Desta Haileselassie Hagos

Reputation: 26086

pre-allocation of array size in Matlab

What is the efficient way of dynamically preallocating the size of an array variable which appears to change its size on every loop iteration in Matlab? It is possible to initialize it using the zeros() matrix but it sometimes is very tricky (for example: in determining the upper and lower limits).

Upvotes: 0

Views: 122

Answers (1)

bla
bla

Reputation: 26069

This is the solution that I use for 2D arrays of dynamic size. Say the maximal limit of my array is 2000x2000, then I just preallocate zeros of the 1-D vector analogue (a 2000^2x1 vector) and after the code ends get rid of the zeros (or just ignore them in case the data is going to a histogram), and reshape once if needed after the code ends...

For example:

 for n=1:100;
     v=zeros(2000^2,1);
     v(1:numel(data))=data(:);
     % rest of the code here
 end

Upvotes: 1

Related Questions