logo

How to Flatten an Array in Julia 📂Julia

How to Flatten an Array in Julia

Code

Use the vec() function.

julia> A = rand(0:9, 3,4)
3×4 Array{Int64,2}:
 6  8  7  3
 2  9  3  2
 5  0  6  7

julia> vec(A)
12-element Array{Int64,1}:
 6
 2
 5
 8
 9
 0
 7
 3
 6
 3
 2
 7

To the human eye, it appears the same as a 1-dimensional array, but it’s actually a 2-dimensional array by type, which can cause errors. This method can solve those cases. The following two commands look exactly the same, but there’s a difference between being a $\mathbb{N}^{10 \times 1}$ matrix or $\mathbb{N}^{10 }$ vector.

julia> b = rand(0:9, 10,1)
10×1 Array{Int64,2}:
 4
 8
 0
 4
 7
 4
 4
 2
 4
 7

julia> vec(b)
10-element Array{Int64,1}:
 4
 8
 0
 4
 7
 4
 4
 2
 4
 7

The Actual flatten() Function

In fact, the real flatten() function is implemented in Base.Iterators. The result of its operation is as follows, and honestly, you might not want to use it. To be more precise, it’s not so much changing the array, but it might be necessary when using it as an iterator in loops or similar contexts. Honestly, it’s unnecessary.

julia> c = rand(0:9, 3,3)
3×3 Matrix{Int64}:
 7  7  4
 9  3  8
 4  4  5

julia> Iterators.flatten(c)
Base.Iterators.Flatten{Matrix{Int64}}([7 7 4; 9 3 8; 4 4 5])

julia> vec(c)
9-element Vector{Int64}:
 7
 9
 4
 7
 3
 4
 4
 8
 5

Environment

  • OS: Windows
  • julia: v1.5.0