Converting Julia nested list to multidimensional array

Viewed 204

Given a Julia list of lists:

data = [[1,2],[4,5]]

which has type Vector{Int64}, how can I convert this to a 2D data type (e.g. 2×2 Matrix{Int64}) so that I can index it like data[:,2]? I tried hcat or vcat but couldn't get the result that I wanted. Thanks in advance!

3 Answers

You can do:

julia> reduce(hcat, data)
2×2 Matrix{Int64}:
 1  4
 2  5

hcat works fine:

julia> hcat([[1,2],[4,5]]...)
2×2 Matrix{Int64}:
 1  4
 2  5

The thing is that vectors are column-vectors in Julia (unlike in NumPy, for example), so you should horisontally concatenate them to get the matrix.

If you use vcat, you'll stack them on top of each other, getting one tall vector:

julia> vcat([[1,2],[4,5]]...)
4-element Vector{Int64}:
 1
 2
 4
 5

You can use Iterators for that. Once you have a Vector simply use reshape.

reshape( collect(Iterators.flatten([[1,2],[4,5]])), 2,2 )

2×2 Matrix{Int64}:
 1  4
 2  5
Related