2

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 3

7

You can do:

julia> reduce(hcat, data)
2×2 Matrix{Int64}:
 1  4
 2  5
Sign up to request clarification or add additional context in comments.

1 Comment

This also works great for splitting strings in matrices: reduce(hcat, split.(readdlm("file.csv"), ""))
3

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

3 Comments

Thanks. I'm used to NumPy indeed, so that extra bit of context helps. What does the ... operator do in this case?
@RvdV, it's the "splat" operator - basically the same as the * operator in function(*[1,2,3,4,5]) in Python
Clear, thanks for your help!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.