Reputation: 466
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
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 h
orisontally concat
enate 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
Reputation: 13800
You can do:
julia> reduce(hcat, data)
2×2 Matrix{Int64}:
1 4
2 5
Upvotes: 7
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