Flattening block matrix (matrix of matrices)

Viewed 85

Consider a 2x2 matrix of 2x2 blocks, e.g.,

using LinearAlgebra
using StaticArrays

M = zeros(SMatrix{2, 2, Float64, 4}, 2, 2)
M[1,1] = SA[1 0; 0 2]
M[2,2] = SA[0 3; 4 0]

What is the best way to convert M into a 4x4 matrix of scalars?

# how to convert M into this?
M2 = [1 0 0 0;
      0 2 0 0;
      0 0 0 3;
      0 0 4 0]

In my real problem the matrix sizes will be larger, but the general question remains: How to flatten a block matrix into one larger matrix.

1 Answers

I recommend using BlockArrays.jl:

julia> using BlockArrays

julia> mortar(M)
2×2-blocked 4×4 BlockMatrix{Float64, Matrix{SMatrix{2, 2, Float64, 4}}, Tuple{BlockedUnitRange{Vector{Int64}}, BlockedUnitRange{Vector{Int64}}}}:
 1.0  0.0  │  0.0  0.0
 0.0  2.0  │  0.0  0.0
 ──────────┼──────────
 0.0  0.0  │  0.0  3.0
 0.0  0.0  │  4.0  0.0

You can of course do Matrix(mortar(M)) to get back to a "normal" matrix. However, if you have this kind of data structure you should like staying with the BlockArray.

Related