MATLAB: Adding sparse matrices efficiently

cell arraymatrix arraymatrix manipulation

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

Best Answer

In general, everytime you add two sparse matrices together a bunch of sparse index sorting etc has to take place first and then the result of the additions gets put into new memory. Doing this at each iteration is what is slowing you down.
If your matrices are only 4000x4000, then maybe adding the individual matrices into a full matrix would be faster since there wouldn't be any need to sort the combined indexes or to put the result into new memory. You could try two different options with this approach.
1) Start with a full 0's matrix and add your sparse matrices into it. A good underlying algorithm will simply add the sparse stuff into the full matrix at the appropriate spots without any index sorting needed. So:
result = zeros(4000,4000);
for k=1:whatever
result = result + A{k};
end
result = sparse(result);
2) Do the equivalent of the above inside a mex routine. That way you could ensure that no large extraneous data copying was taking place, but everything was simply added directly into the result. This mex routine would not be too difficult to write. If you opt for this method let me know and I can help.