MATLAB: Construct a large sparse matrix

MATLABmatrix sparsity

Hi, everyone
I am currently constructing a very large sparse square matrix which is made by several smaller sparse matrices, for example:
A is a n-by-n sparse matrix, B is a m-by-m sparse matrix.
if I want to produce another matrix J=blkdiag(A,B), do I have to put sparse command outside blkdiag? i.e. J=sparse(blkdiag(A,B))
Similar for H=kron(A,B), is there any improvement at all if write H=sparse(kron(A,B))?

Best Answer

Nowadays most functions are able to work on sparse matrices and output sparse matrices. If you want to be sure that it is working, use ISSPARSE to check on a small case study, e.g.
>> A = sparse([2 0 3; 4 5 0; 0 0 6]) ;
>> B = sparse([0 1 0; 2 0 2; 3 3 0]) ;
>> C = kron(A, B) ;
>> issparse(C)
ans =
1
>> C = blkdiag(A, B) ;
>> issparse(C)
ans =
1
There is no advantage in using SPARSE on a matrix that is already sparse.
Note that the situation where you convert a dense version of a large matrix to sparse can/should rarely happen. You generally have to build the matrix directly as a sparse matrix, using a call like
S = sparse(I, J, V, m, n) ;
where I and J are vectors of respectively row and column indices, V is a vector of values, and m and n define the size.
One of the rare cases where you transform a dense matrix to sparse is when you build a small matrix that must be used as a basis for building a larger one, which seems to be your case.