MATLAB: Matrix pre-allocation

matrixmemory

What's actually the difference between the following commands
sparse(zeros(10000));
sparse([],[],[],10000,10000,0);
a = sparse([]); for i =1:10000,for j = 1:10000, a(i,j) = 0,end,end
Oftentimes the first line leads to out-of-memory problem while the rest do not when the dimension acretes.
I consulted to some tutorial about memory allocation that says "loop" is at times useful to speed up and avoid memory outflow.
When should I use loop to generate a really "big" matrix? or the second line just dominates?
Thanks

Best Answer

The first command creates the full array zeros(10000) before turning it into a sparse array. The simplest way of creating the matrix you want is
sparse(10000,10000)
This is not a problem where using a loop is a good idea! You can time the commands using tic and toc:
tic
a = sparse([]); for i =1:100,for j = 1:100, a(i,j) = 0; end,end
toc
tic
b = sparse(100,100);
toc
On my computer, the output is
Elapsed time is 0.010886 seconds.
Elapsed time is 0.000298 seconds.
In other words, for an array that is only 100 x 100, the loops are 35 times slower. If you increase the array size, the loops increase in time as the total number of elements, while the second command always takes about the same time. So with your array, the loops would to it 350,000 times slower! And that's assuming that you change the comma after a(i,j) = 0 to a semicolon so the output isn't displayed after each element is changed.