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).
Asked
Active
Viewed 79 times
0

Desta Haileselassie Hagos
- 23,140
- 7
- 48
- 53
-
from my experience, easiest and best to preallocate for some maximal size and then get rid of zeros later... how big is your biggest array? – bla Dec 14 '15 at 04:26
-
For example, I have one array of length 1050. – Desta Haileselassie Hagos Dec 14 '15 at 04:31
-
you mean 1050x1050 ? – bla Dec 14 '15 at 04:37
-
Yes, an array of 1050x1050. – Desta Haileselassie Hagos Dec 14 '15 at 04:39
-
1on a side note, depending on your matlab version and array size, try preallocate using different methods as detailed in this discussion: http://stackoverflow.com/questions/14169222/faster-way-to-initialize-arrays-via-empty-matrix-multiplication-matlab – bla Dec 14 '15 at 04:41
1 Answers
1
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

bla
- 25,846
- 10
- 70
- 101