Constructing a block tri-diagonal matrix

I need to construct a matrix of this form:

image

where A1, A2, ..., A_M are given (rectangular) matrices, and the zeros are blocks of appropriate sizes.

How can I do this in Julia, with as less code as possible? Maybe there is a package I can use?

There is the function SparseArrays.blockdiag which does something close, but only works for sparse arrays. The matrices I have are not sparse.

A generalization of this is to construct block tridiagonal matrices (https://en.wikipedia.org/wiki/Block_matrix#Block_tridiagonal_matrices). But I haven’t found any packages for this.

Well, you can always call Matrix on the result to convert the final result to a dense matrix. (This is not the most efficient possible way, but you asked for a minimal-code solution.)

1 Like

Actually blockdiag doesn’t let me interleave the 0 blocks, which are shared in my case between one block and the next. Also for large matrices the dense -> sparse -> dense conversions are too slow, I think.

Have you tried BlockBandedMatrices.jl?

1 Like

Maybe I did not understand this package well, I just read the docs now. But I think it deals with matrices where the blocks are banded? I rather need a to build a matrix the bands are blocks.

https://juliaarrays.github.io/BlockArrays.jl/stable/man/blockarrays/

1 Like

Can you show an example? I’m not sure how I can use this package to do what I want.

julia> using BlockBandedMatrices
[ Info: Precompiling BlockBandedMatrices [ffab5731-97b5-5995-9138-79e8c1846df0]

julia> A = BlockTridiagonal(fill([1 2],3), fill([3 4],4), fill([4 5],3))
4Γ—4-blocked 4Γ—8 BlockArrays.BlockArray{Int64,2,Tridiagonal{Array{Int64,2},Array{Array{Int64,2},1}},Tuple{BlockArrays.BlockedUnitRange{Array{Int64,1}},BlockArrays.BlockedUnitRange{Array{Int64,1}}}}:
 3  4  β”‚  4  5  β”‚  β‹…  β‹…  β”‚  β‹…  β‹…
 ──────┼────────┼────────┼──────
 1  2  β”‚  3  4  β”‚  4  5  β”‚  β‹…  β‹…
 ──────┼────────┼────────┼──────
 β‹…  β‹…  β”‚  1  2  β”‚  3  4  β”‚  4  5
 ──────┼────────┼────────┼──────
 β‹…  β‹…  β”‚  β‹…  β‹…  β”‚  1  2  β”‚  3  4

3 Likes