Turn an Expr into an array in julia

Viewed 56

I have an Expr

:([4.01673077 7.62137432 8.74459436 10.14775067 12.57379884 14.39781963; 17.00925227 19.2273262])

and I wish to transfer it into a Vector{Float64}, but calling eval on this directly does not seem to work.

How can I do this?

1 Answers

You can either extract the data from Expr (faster and safe) or just eval it (slower, unsafe, easier code).

julia> a  = :([12.57379884 14.39781963; 17.00925227 19.2273262])
:([12.57379884 14.39781963; 17.00925227 19.2273262])

julia> [Float64.(vals) for vals in getfield.(a.args, :args)]
2-element Vector{Vector{Float64}}:
 [12.57379884, 14.39781963]
 [17.00925227, 19.2273262]

julia> eval(a)
2×2 Matrix{Float64}:
 12.5738  14.3978
 17.0093  19.2273

Your matrix is wrongly formed and hence only the first solution will work with it.

Related