'Concatenating arrays in Julia

If the two Int arrays are, a = [1;2;3] and b = [4;5;6], how do we concatenate the two arrays in both the dimensions? The expected outputs are,

julia> out1
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

julia> out2
3x2 Array{Int64,2}:
 1  4
 2  5
 3  6


Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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

Solution 4:[4]

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

Solution 5:[5]

Functional way to concatanate 2 arrays is to use reduce function.

a = rand(10, 1)
b = rand(10, 1)
c = reduce(hcat, [ a, b])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HarmonicaMuse
Solution 2 user6847814
Solution 3 Landon
Solution 4 Jason D
Solution 5 Kadir Gunel