MATLAB: How to create a sparse matrix containing (3,3) block matrices on the main diagonal and on diagonals below and above the main diagonal without using loops

block matricessparse matrixspdiags

The idea is to create a (3m,3m) sparse matrix with small (3,3) matrices on the main diagonal and on diagonals below and above the main diagonal. By saying this, I want that each time the main diagonal of the small (3,3) matrix is on the main diagonal or on another diagonal respectively. There is no gap between the small (3,3) matrices on the diagonals. How can I use the functions sparse, spdiags, blkdiag to create this matrix? If there are other functions guaranteeing sparsity that's fine.

Best Answer

BLKDIAG will give you a sparse matrix if one of its inputs is sparse. Try building the 3x3 matrices as sparse, or converting them (or just one) to sparse, before using BLKDIAG; it should work fine.