Using 5 input arguments with the sparse command is indeed an efficient way to construct a sparse matrix. However, you most likely will not be able to speed up the call to sparse, because no matter how the matrix is constructed there is some overhead cost in storing it.
Specifically, MATLAB uses an efficient storage format for sparse matrices. Rather than store the column indices of the non-zero elements, sparse matrices instead store a vector that holds, for each column, the total number of nonzero elements in all preceding columns. The purpose of this is to reduce the overall storage, as in most cases the total number of non-zeros is greater than the number of columns. However, it also means that sparse has to compute the entries of this vector, which introduces overhead. The suggested test for your code demonstrates quite well why this system is beneficial. When I run the test, I produce the following sparse matrix X:
>> whos X
Name Size Bytes Class Attributes
X 90000x90000 1175152232 double sparse
The memory used by X is given by the formula
>> int32(2*8*nnz(X) + (size(X,2)+1)*8)
ans =
1175152232
The first term is the cost of storing the values of the entries and their row indices, and the second is the cost of storing the column data. Compare this with the cost of storing the both the column and row indices:
>> int32(3*8*nnz(X))
ans =
1761648336
So MATLAB's format saves 586 MB of memory, but it comes at the cost of a more time-consuming initialization.
Best Answer