RvdV
RvdV

Reputation: 466

Converting Julia nested list to multidimensional array

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!

Upvotes: 2

Views: 1089

Answers (3)

ForceBru
ForceBru

Reputation: 44886

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

Upvotes: 3

Nils Gudat
Nils Gudat

Reputation: 13800

You can do:

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

Upvotes: 7

Andre Wildberg
Andre Wildberg

Reputation: 19191

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

Upvotes: 2

Related Questions