I have an MxM
matrix S
whose entries are zero on the diagonal, and non-zero everywhere else. I need to make a larger, block matrix. The blocks will be size NxN
, and there will be MxM
of them.
The (i,j)th
block will be S(i,j)I
where I=eye(N)
is the NxN
identity. This matrix will certainly be sparse, S
has M^2-M
nonzero entries and my block matrix will have N(M^2-M)
out of (NM)^2
or about 1/N
% nonzero entries, but I'll be adding it to another NMxNM
matrix that I do not expect to be sparse.
Since I will be adding my block matrix to a full matrix, would there be any speed gain by trying to write my code in a 'sparse' way? I keep going back and forth, but my thinking is settling on: even if my code to turn S
into a sparse block matrix isn't very efficient, when I tell it to add a full and sparse matrix together, wouldn't MATLAB know that it only needs to iterate over the nonzero elements? I've been trained that for
loops are slow in MATLAB and things like repmat
and padding with zeros is faster, but my guess is that the fastest thing to do would be to not even build the block matrix at all, but write code that adds the entries of (the small matrix) S
to my other (large, full) matrix in a sparse way. If I were to learn how to build the block matrix with sparse code (faster than building it in a full way and passing it to sparse
), then that code should be able to do the addition for me in a sparse way without even needing to build the block matrix right?