Concatenating arrays in Julia

Square brackets can be used for concatenation:

julia> a, b = [1;2;3], [4;5;6]
([1,2,3],[4,5,6])

julia> [a; b]
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

julia> [a b]
3×2 Array{Int64,2}:
 1  4
 2  5
 3  6

Use the vcat and hcat functions:

julia> a, b = [1;2;3], [4;5;6]
([1,2,3],[4,5,6])

help?> vcat
Base.vcat(A...)

   Concatenate along dimension 1

julia> vcat(a, b)
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

help?> hcat
Base.hcat(A...)

   Concatenate along dimension 2

julia> hcat(a, b)
3x2 Array{Int64,2}:
 1  4
 2  5
 3  6

when encountered Array{Array,1}, the grammer is a little bit different, like this:

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

julia> vcat(a)
2-element Array{Array{Int64,1},1}:
 [1, 2]
 [3, 4]

julia> hcat(a)
2×1 Array{Array{Int64,1},2}:
 [1, 2]
 [3, 4]

julia> vcat(a...)
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> hcat(a...)
2×2 Array{Int64,2}:
 1  3
 2  4

ref:

... combines many arguments into one argument in function definitions In the context of function definitions, the ... operator is used to combine many different arguments into a single argument. This use of ... for combining many different arguments into a single argument is called slurping


You can use the cat function to concatenate any number of arrays along any dimension. The first input is the dimension over which to perform the concatenation; the remaining inputs are all of the arrays you wish to concatenate together

a = [1;2;3]
b = [4;5;6]

## Concatenate 2 arrays along the first dimension
cat(1,a,b)
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

## Concatenate 2 arrays along the second dimension
cat(2,a,b)
3x2 Array{Int64,2}:
 1  4
 2  5
 3  6

## Concatenate 2 arrays along the third dimension
cat(3,a,b)
3x1x2 Array{Int64,3}:
[:, :, 1] =
 1
 2
 3

[:, :, 2] =
 4
 5
 6

Tags:

Julia