Increased time for setting elements in sparse matrix
Afficher commentaires plus anciens
Hi Everyone,
I am trying to create a large sparse matrix. After creating the matrix I set elements by creating blkdiag matrices in a for loop.
However, each iteration of the for loop takes longer than the previous one.
Is there a more efficient way to set the elements?
I created a small code fragment to highlight the issue:

n=80000;
m=80000;
p=500;
H=sparse(n,m);
time_vec=zeros(n/p,1);
for i=1:n/p
t1=tic;
dat_cells=repmat({1:n/p},1,p);
H((i-1)*p+1:(i)*p,:)=sparse(blkdiag(dat_cells{:}));
time_vec(i)=toc(t1);
end
figure,plot(time_vec)
Réponses (1)
James Tursa
le 6 Juil 2022
1 vote
Every time you change the elements of a sparse matrix, MATLAB has to deep copy all the existing elements to a newly allocated chunk of memory with enough room for the current elements and your new elements. If you do this repeatedly, the same elements get deep copied over and over again. This is the drag on your performance. If possible in your application, it is better to generate all the new elements off to the side and then add them into the sparse matrix all at once instead of piecemeal.
1 commentaire
Markus Adamek
le 6 Juil 2022
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!