Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I efficiently construct a block matrix of the following form in JULIA?

Tags:

matrix

julia

So I am working on a code that requires me to construct a large Matrix M using smaller 'square' matrices J AND M of sizes n x n each, repeated such that:

This is what the matrix should look like!

i.e with the dimensions of M such that M is repeated 'L' times along the diagonal, J' is repeated along the upper second diagonal and J on the lower second diagonal.

Note that I am working on Julia v 1.0.0 and as far as I understand there are no direct ways of assigning Block Matrices in Julia, unlike Mathematica.

I tried to use Kronecker products to solve my problem:

 𝐈=Diagonal(ones(L)) #IDENTITY matrix of L x L size
 𝐌=kron(𝐈,M)

Doing so, I can make a Block diagonal matrix M with small matrix M repeated along its diagonal. But now how do I place matrices J and J' along its second diagonals as required?

like image 908
akira Avatar asked Jan 02 '23 08:01

akira


1 Answers

BlockArrays.jl (and maybe BlockBandedMatrices.jl) should be what you are looking for as it makes handling block matrix structures very convenient.

An example (with Stringss):

julia> using BlockArrays

julia> M = fill("M", 2,2);

julia> J = fill("J", 2,2);

julia> B = BlockArray{String}(undef_blocks, [2,2], [2,2])
4Γ—4 BlockArray{String,2,Array{String,2}}:
 #undef  #undef  β”‚  #undef  #undef
 #undef  #undef  β”‚  #undef  #undef
 ────────────────┼────────────────
 #undef  #undef  β”‚  #undef  #undef
 #undef  #undef  β”‚  #undef  #undef

julia> setblock!(B, M, 1,1);

julia> setblock!(B, M, 2,2);

julia> setblock!(B, J, 1,2);

julia> setblock!(B, J, 2,1);

julia> B
4Γ—4 BlockArray{String,2,Array{String,2}}:
 "M"  "M"  β”‚  "J"  "J"
 "M"  "M"  β”‚  "J"  "J"
 ──────────┼──────────
 "J"  "J"  β”‚  "M"  "M"
 "J"  "J"  β”‚  "M"  "M"

For more information, check out the package's documentation.

like image 123
carstenbauer Avatar answered May 24 '23 06:05

carstenbauer