Julia Language Concatenation


Example

It is often useful to build matrices out of smaller matrices.

Horizontal Concatenation

Matrices (and vectors, which are treated as column vectors) can be horizontally concatenated using the hcat function.

julia> hcat([1 2; 3 4], [5 6 7; 8 9 10], [11, 12])
2×6 Array{Int64,2}:
 1  2  5  6   7  11
 3  4  8  9  10  12

There is convenience syntax available, using square bracket notation and spaces:

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

This notation can closely match the notation for block matrices used in linear algebra:

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

julia> B = [5 6; 7 8]
2×2 Array{Int64,2}:
 5  6
 7  8

julia> [A B]
2×4 Array{Int64,2}:
 1  2  5  6
 3  4  7  8

Note that you cannot horizontally concatenate a single matrix using the [] syntax, as that would instead create a one-element vector of matrices:

julia> [A]
1-element Array{Array{Int64,2},1}:
 [1 2; 3 4]

Vertical Concatenation

Vertical concatenation is like horizontal concatenation, but in the vertical direction. The function for vertical concatenation is vcat.

julia> vcat([1 2; 3 4], [5 6; 7 8; 9 10], [11 12])
6×2 Array{Int64,2}:
  1   2
  3   4
  5   6
  7   8
  9  10
 11  12

Alternatively, square bracket notation can be used with semicolons ; as the delimiter:

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

Vectors can be vertically concatenated too; the result is a vector:

julia> A = [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> B = [4, 5]
2-element Array{Int64,1}:
 4
 5

julia> [A; B]
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

Horizontal and vertical concatenation can be combined:

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

julia> B = [5 6 7]
1×3 Array{Int64,2}:
 5  6  7

julia> C = [8, 9]
2-element Array{Int64,1}:
 8
 9

julia> [A C; B]
3×3 Array{Int64,2}:
 1  2  8
 3  4  9
 5  6  7