MATLAB: How to shrink the memory footprint of a sparse matrix to its minimum

MATLABmemorynnzspallocsparse

How do I shrink the memory footprint of a sparse matrix to its minimum?
When I construct a sparse matrix, I do not know upfront how many non-zero entries I need. I specify an upper bound and construct my matrix, later finding that many of these elements are unused. I want to recover the unused memory from this sparse matrix.
Calling the 'spalloc()' function allocates memory for a sparse m-by-n matrix with 'nz' non-zero entries (see
). There is no function to change 'nz' after constructing the sparse matrix, in order to free unused memory.

Best Answer

A workaround to free unused memory in 'X' is to first construct a temporary sparse matrix 'Y', with the exact number of non-zero elements needed, second, copy the elements of 'X' into 'Y', and third, delete 'X'. The number of non-zero elements can be found using the function 'nnz'.
For example,
X = spalloc(1e6,1e6,1e4);
X(1,1) = 1;
Y = spalloc( size(X,1) , size(X,2) , nnz(X) ); % constructs the temporary sparse matrix of minimal memory
Y(:,:) = X(:,:); % element wise assignment
clear X;
This workaround will require sufficient memory in the first instance to construct the temporary sparse matrix 'Y'.