Storage of sparse matrices
1 view (last 30 days)
Show older comments
Christophe Langrenne
on 3 Nov 2014
Answered: John D'Errico
on 3 Nov 2014
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
0 Comments
Accepted Answer
John D'Errico
on 3 Nov 2014
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.
0 Comments
More Answers (0)
See Also
Categories
Find more on Sparse Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!