Increased time for setting elements in sparse matrix
显示 更早的评论
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)
回答(1 个)
James Tursa
2022-7-6
1 个投票
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!