MATLAB: Storage of sparse matrices

sparse matrixstorage

Hi,
I have a problem to create a sparse matrix in a loop. I use the following code :
% init the sparse matrix to zeros with ns=272 and nc = 50
B=sparse(ns*nc,ns*nc);
% in the loop I do
tic
B=B+sparse(ii,jj,M2L,ns*nc,ns*nc);
toc
with ii, jj, M2L a vector of dim=50 x 1
The code takes 0.0002 sec in the beginning, but the time increases gradually (It can take about 0.0383 sec after).
What can I do to reduce this time of storage ?
Best regards

Best Answer

Use of sparse calls in this way is an obscenity. I'm sorry to say that, but it is so.
Make ONE call to sparse, AFTER you have generated all of the elements up front. And don't grow the array of data as you build it, as that too will be a quadratically increasing operation. Preallocate the array to contain your elements. ONLY then make one call to sparse.
Related Question