logo

Tricks for Concatenating Arrays of Arrays in Julia 📂Julia

Tricks for Concatenating Arrays of Arrays in Julia

Overview

In Julia, although you can concatenate arrays using functions like append!, the bang convention implies that the original array is modified as a side effect. To avoid this, we introduce a trick using the splat operator ....

Code

Merging Arrays of Different Lengths

julia> y = [[3, 1, 4], [1, 5], [9, 2]]
3-element Vector{Vector{Int64}}:
 [3, 1, 4]
 [1, 5]
 [9, 2]

julia> [y...;]
7-element Vector{Int64}:
 3
 1
 4
 1
 5
 9
 2

A semicolon ; at the end of the array enumeration y... results in array merging. This returns the same result as [y[1]; y[2]; y[3]], or more elegantly, vcat(x...).

Vertical Concatenation [x...;]

If the dimensions of matrices match, there is no reason they cannot be merged since matrices possess properties of arrays. For multidimensional concatenation, it returns the same result as cat(x..., dims=n) for the number of semicolons n following x.... This may be difficult to understand in words, so let’s verify with a concrete example.

julia> x = [reshape(1:4, 2, 2), reshape(5:8, 2, 2), reshape(9:12, 2, 2)];

julia> x[1]
2×2 reshape(::UnitRange{Int64}, 2, 2) with eltype Int64:
 1  3
 2  4

julia> x[2]
2×2 reshape(::UnitRange{Int64}, 2, 2) with eltype Int64:
 5  7
 6  8

julia> x[3]
2×2 reshape(::UnitRange{Int64}, 2, 2) with eltype Int64:
  9  11
 10  12

Assume you have a given array of 2D arrays as above.

julia> [x...;]
6×2 Matrix{Int64}:
  1   3
  2   4
  5   7
  6   8
  9  11
 10  12

julia> [x...;] == cat(x..., dims = 1)
true

[x...;] returns a matrix vertically merged, equivalent to cat(x..., dims = 1).

Horizontal Concatenation [x...;;]

julia> [x...;;]
2×6 Matrix{Int64}:
 1  3  5  7   9  11
 2  4  6  8  10  12

julia> [x...;;] == cat(x..., dims = 2)
true

[x...;;], with two semicolons, returns a matrix horizontally merged, equivalent to cat(x..., dims = 2).

Depth Concatenation [x...;;;]

julia> [x...;;;]
2×2×3 Array{Int64, 3}:
[:, :, 1] =
 1  3
 2  4

[:, :, 2] =
 5  7
 6  8

[:, :, 3] =
  9  11
 10  12

julia> [x...;;;] == cat(x..., dims = 3)
true

There’s no reason tensors can’t be manipulated in this way. [x...;;;] with three semicolons returns a tensor stacked in depth, equivalent to cat(x..., dims = 3).

Complete Code

y = [[3, 1, 4], [1, 5], [9, 2]]
[y...;]

x = [reshape(1:4, 2, 2), reshape(5:8, 2, 2), reshape(9:12, 2, 2)];
x[1]
x[2]
x[3]

[x...;]
[x...;] == cat(x..., dims = 1)

[x...;;]
[x...;;] == cat(x..., dims = 2)

[x...;;;]
[x...;;;] == cat(x..., dims = 3)

Environment

  • OS: Windows
  • julia: v1.11.1