How do I change the data type of a Julia array from "Any" to "Float64"?

P4nd4b0b3r1n0 picture P4nd4b0b3r1n0 · Feb 18, 2016 · Viewed 15.8k times · Source

Is there a function in Julia that returns a copy of an array in a desired type, i.e., an equivalent of numpys astype function? I have an "Any" type array, and want to convert it to a Float array. I tried:

new_array = Float64(array)

but I get the following error

LoadError: MethodError: `convert` has no method matching 
convert(::Type{Float64}, ::Array{Any,2})
This may have arisen from a call to the constructor Float64(...),
since type constructors fall back to convert methods.
Closest candidates are:
  call{T}(::Type{T}, ::Any)
  convert(::Type{Float64}, !Matched::Int8)
  convert(::Type{Float64}, !Matched::Int16)
  ...
  while loading In[140], in expression starting on line 1

  in call at essentials.jl:56

I can just write a function that goes through the array and returns a float value of each element, but I find it a little odd if there's no built-in method to do this.

Answer

Randy Zwitch picture Randy Zwitch · Feb 18, 2016

Use convert. Note the syntax I used for the first array; if you know what you want before the array is created, you can declare the type in front of the square brackets. Any just as easily could've been replaced with Float64 and eliminated the need for the convert function.

julia> a = Any[1.2, 3, 7]
3-element Array{Any,1}:
 1.2
 3  
 7  

julia> convert(Array{Float64,1}, a)
3-element Array{Float64,1}:
 1.2
 3.0
 7.0