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

 Respuesta aceptada

John D'Errico
John D'Errico el 3 de Nov. de 2014

2 votos

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.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by