Concatenate matrices without specifying the size of zero matrices

I wonder if there is a way to concatenate matrices without the need to specifying the size of the zero portions.
For square matrices, I have a clever idea as follows

julia> using LinearAlgebra

julia> A = rand(-9:9, 2, 2)
2×2 Matrix{Int64}:
  8  -1
 -8  -5

julia> B = rand(-9:9, 2, 2)
2×2 Matrix{Int64}:
  9   4
 -9  -4

julia> desired = [A false*I; false*I B]
4×4 Matrix{Int64}:
  8  -1   0   0
 -8  -5   0   0
  0   0   9   4
  0   0  -9  -4

But what about for a rectangular matrix?

julia> C = rand(-9:9, 3, 3)
3×3 Matrix{Int64}:
 -4  -8   5
  9  -6   0
 -8  -8  -2

julia> desired = [A zeros(2, 3); zeros(3, 2) C] # I have to do this
5×5 Matrix{Float64}:
  8.0  -1.0   0.0   0.0   0.0
 -8.0  -5.0   0.0   0.0   0.0
  0.0   0.0  -4.0  -8.0   5.0
  0.0   0.0   9.0  -6.0   0.0
  0.0   0.0  -8.0  -8.0  -2.0

Does there exist a more appropriate method?

Perhaps use BlockDiagonals.jl?

1 Like

cat(A, B, dims=(1,2))

1 Like