# How to add two sparse matrices or ndSparse matrices in MATLAB?

8 views (last 30 days)
Jakob Havtorn on 13 Oct 2016
Commented: Jakob Havtorn on 18 Nov 2017
I am aware that sparse matrices are most effciently worked with when they are created at once from a set of indices and values.
However, due to the size of my data, I am unable to store all indices and values at once, and am forced to batch my execution, so that a sparse matrix is built from a set of indices and values once in a while (say every 100th input file).
This introduces the problem of how to add two sparse matrices, which are not guaranteed to have the same dimension, as I need to accumulate the values (add them) if indices are identical.
I am currently using the ndSparse class from File Exchange, but would also be interested in an answer for MATLAB's built-in sparse function.
The main problem lies in making sure both sparse matrices have the same dimension. Is there any smart/efficient way to do this? Using padarray is not an option.
Jakob Havtorn on 18 Nov 2017
As far as I recall, I ended up doing a couple of if-statements to check whether the dimensions of the two ndSparse matrices were identical. If not, I would obtain the dimension of the larger of the matrices and index into the smaller of the matrices at this index and assign a zero.
This dynamically allocates the extra space for the single zero while increasing the dimension available for assignment in the smaller matrix to match that of the larger. The two matrices can then be added as usual.
I found that the if statements and the dynamic allocation of a single double did not reduce the performance significantly (only a few scalar operations compared to addition of large, but sparse, matrices).

Johannes Korsawe on 14 Oct 2016
help sparse
fourth and fifth argument of sparse prescribe the dimensions. If you know them from the beginning of ayour code, you can define all matrices of the same size and add them regularly.