# Concatenate matrices without specifying the size of zero matrices

**URL:** <https://discourse.julialang.org/t/concatenate-matrices-without-specifying-the-size-of-zero-matrices/128681>\
**Category:** New to Julia\
**Tags:** question, linearalgebra, identity\
**Created:** [May 4, 2025, 6:39am UTC](https://discourse.julialang.org/t/concatenate-matrices-without-specifying-the-size-of-zero-matrices/128681 "2025-05-04T06:39:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![WalterMadelim](https://avatars.discourse-cdn.com/v4/letter/w/3e96dc/32.png) [@WalterMadelim](https://discourse.julialang.org/u/WalterMadelim)\
**Post date:** [May 4, 2025, 6:39am UTC](https://discourse.julialang.org/t/concatenate-matrices-without-specifying-the-size-of-zero-matrices/128681/1 "2025-05-04T06:39:23Z")

</div>

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
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
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?

---

<div class="post-metadata">

**Author:** ![niro](https://avatars.discourse-cdn.com/v4/letter/n/bb73d2/32.png) [@niro](https://discourse.julialang.org/u/niro)\
**Post date:** [May 4, 2025, 7:37am UTC](https://discourse.julialang.org/t/concatenate-matrices-without-specifying-the-size-of-zero-matrices/128681/2 "2025-05-04T07:37:02Z")

</div>

Perhaps use BlockDiagonals.jl?

---

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [May 4, 2025, 7:37am UTC](https://discourse.julialang.org/t/concatenate-matrices-without-specifying-the-size-of-zero-matrices/128681/3 "2025-05-04T07:37:14Z")

</div>

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