Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert data type of any to float in matrix in Julia

Tags:

julia

I have a matrix(rand2) of type "any", and I want to convert the type to float. I have following code.

for i in 1:size(rand2,1)
   rand2[i,:]=convert(Array{Float64,1}, rand2[i,:])
end

Such code will not change the data type. What‘s the issue here?

like image 664
Josie G Avatar asked Oct 18 '25 12:10

Josie G


1 Answers

Use dot operator to vectorize over type conversion.

Suppose you have

julia> m = Matrix{Any}(rand(2,2))
2×2 Matrix{Any}:
 0.250737  0.0366769
 0.240182  0.883665

Than you could do

julia> Float64.(m)
2×2 Matrix{Float64}:
 0.250737  0.0366769
 0.240182  0.883665

or you could explicitly call vectorized convert:

julia> convert.(Float64, m)
2×2 Matrix{Float64}:
 0.250737  0.0366769
 0.240182  0.883665
like image 174
Przemyslaw Szufel Avatar answered Oct 21 '25 07:10

Przemyslaw Szufel