MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today**New to MATLAB?**

Asked by Manuel
on 19 May 2013

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.

*No products are associated with this question.*

Answer by Cedric Wannaz
on 20 May 2013

Accepted 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.

Answer by Iain
on 20 May 2013

You can initialise a sparse matrix as:

matrix = sparse(zeros(3*m,3*m));

If you then use it as:

matrix(1:3,1:3) = [a b c; d e f; g h i];

matrix(3+1:3,3+1:3) = [j k l; m n o; p q r];

... etc you will get what I think you're asking for.

## 2 Comments

## Cedric Wannaz (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/76326#comment_149785

Did you generate these

m3x3 sparse matrices already or do you want to avoid building them and build directly the block diagonal large sparse matrix? If you have these small matrices already defined, what have you tried so far using BLKDIAG?## Manuel (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/76326#comment_149844

I've got all the 3x3 matrices (they are not sparse) already. Basically they are the local Hessian operator on a manifold. Now I want to store them in this huge sparse matrix to do a Newton step (Newton Method). I've thought of using the Tensor Toolbox since blkdiag doesn't give me a sparse matrix.