How to create sparse matrix with blkdiag ?

16 views (last 30 days)
Arc Lok
Arc Lok on 20 Dec 2015
Edited: Walter Roberson on 20 Dec 2015
Hello guys,
I have a matrix "param" of size (N,3,3) with N being relatively large. I want to create a sparse 3*N*N square matrix whose diagonals are param(1,:,:) which are 3x3 matrix. Here is what I do:
paramC=num2cell(param,[2 3]);
DiagMatrix=blkdiag(paramC{:});
But, when I try to do that I have a memory problem when calling blkdiag, arguing that the matrix is too large (3*N*N square matrix). But the matrix should be really sparse as it is a tridiagonal matrix.
I have tried multiple way to make matlab understand that this is a sparse matrix include:
paramC=num2cell(sparse(param),[2 3]);
DiagMatrix=blkdiag(paramC{:});
paramC=num2cell(param,[2 3]);
DiagMatrix=blkdiag(sparse(paramC{:}));
but everytime I get the error:
Undefined function 'sparse' for input arguments of type 'double' and attributes 'full 3d real'.
Do you have a way to fix this issue ?
Thanks a lot !

Answers (2)

John D'Errico
John D'Errico on 20 Dec 2015
Edited: John D'Errico on 20 Dec 2015
A sparse tridiagonal matrix, built directly from the diagonal elements is one of the things that my blktridiag can build. It is on the file exchange.
It is a bit unclear if your goal is to build a block diagonal matrix or a tridiagonal matrix, or exactly what. For example, you can use spdiags to build a sparse tridiagonal matrix. And you CAN use blkdiag to build a sparse block diagonal matrix. You need to force each block to be itself sparse.
C = {sparse(rand(3)),sparse(rand(3)),sparse(rand(3))};
A = blkdiag(C{:});
whos A
Name Size Bytes Class Attributes
A 9x9 512 double sparse
spy(A)

Walter Roberson
Walter Roberson on 20 Dec 2015
Edited: Walter Roberson on 20 Dec 2015
You face the fundamental problem that in MATLAB, only 2D sparse matrices are supported, not 3D.
"accumarray groups data into bins using n-dimensional subscripts, but sparse groups data into bins using 2-D subscripts."

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!