Adding sparse matrices efficiently?
Afficher commentaires plus anciens
Hi, I have a cell array which consists of many sparse matrices. For example:
N.B. In my original problem each sparse matrix is about 4000*4000 in size and has many zero entries
A{1}=sparse(magic(150));
A{2}=sparse(magic(150));
A{3}=sparse(magic(150));
A{4}=sparse(magic(150));
....
% I want something like:
KK = A{1}+A{2}+A{3}+....
% KK should be a sparse matrix of 150*150
% Adding them in a loop is very time consuming
% I tried the following but did not work:
KK = sum(cat(2,KC{:}),3); % or 1,2 as the sum dimension
% also
KK = sum([KC{:}]); % gives a vector
2 commentaires
David Goodmanson
le 17 Nov 2018
Hi Mohammod,
It's not going to be a good idea to use sparse(magic(N)) as a benchmark for timing. This matrix is stored in the sparse convention but is absolutely not sparse, since it has no nonzero elements at all. Sparse has to do a lot of work in that case.
sparse(magic(N)) + sparse(magic(N)) takes more time than the addition of the full matrices, magic(N) + magic(N).
Mohammod Minhajur Rahman
le 17 Nov 2018
Réponse acceptée
Plus de réponses (1)
Bruno Luong
le 17 Nov 2018
Modifié(e) : Bruno Luong
le 17 Nov 2018
The fatest way to add sparse matrices is to build the sum from scratch.
It takes 4 second for 1000 random matrices of 4000x4000 with density 1e-3.
I = [];
J = [];
V = [];
n = 0;
for k = 1:length(A)
[i,j,v] = find(A{k});
p = n + numel(i);
m = numel(I);
if p > m
m = max(p,2*m);
I(m) = 0;
J(m) = 0;
V(m) = 0;
end
idx = (n+1:p);
I(idx) = i;
J(idx) = j;
V(idx) = v;
n = p;
end
idx = (n+1:numel(I));
I(idx) = [];
J(idx) = [];
V(idx) = [];
[m,n] = size(A{1});
SUM = sparse(I,J,V,m,n)
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!