user5739619
user5739619

Reputation: 1838

Convert float64 3-D array to float32 3-D array in Julia

I tried the following, but none of them worked

A = zeros(2,2,2)
A[:,:,1] = [1 2; 3 4]
A[:,:,2] = [10 20; 30 40]

for i=1:size(A,1)
    convert(Array{Float32,2}, A[i,:,:])
end

print(typeof(A))

Output: Array{Float64,3}

convert(Array{Float32,3}, A)
print(typeof(A))

Output: Array{Float64,3}

map(y->(Float32,y), A)
print(typeof(A))

Output: Array{Float64,3}

I can't even convert the array of Float64 to an array of Int:

for i=1:size(A,1)
    round.(Int,  A[i,:,:])
end

print(typeof(A))

Output: Array{Float64,3}

Anything else I can do to try to convert this from Array{Float64,3} to Array{Float32,3}?

Upvotes: 1

Views: 2908

Answers (4)

DNF
DNF

Reputation: 12644

There's nothing wrong with the way you're calling convert. It works completely fine.

But convert doesn't work in-place. Instead it creates a new array, which you have to assign to an output variable (it also works if you re-assign the new array back to A):

julia> A = rand(2,2,2);

julia> B = convert(Array{Float32, 3}, A); # this does *not* change A

julia> typeof(A) # A is not changed
  Array{Float64,3}

julia> typeof(B) # this is the converted array
  Array{Float32,3}

julia> A = convert(Array{Float32, 3}, A);

julia> typeof(A)
  Array{Float32,3}

You can also use the other suggested solutions, such as Float32.(A), but that is not your problem.

Upvotes: 0

nbwoodward
nbwoodward

Reputation: 3156

Your convert syntax is close. You can just do:

B = convert(Array{Float32},A)

Upvotes: 0

hesham_EE
hesham_EE

Reputation: 1165

A = zeros(2,2,2)
A[:,:,1] = [1 2; 3 4]
A[:,:,2] = [10 20; 30 40]

Use Float32.(A)

julia> A=Float32.(A)
2×2×2 Array{Float32,3}:
[:, :, 1] =
 1.0  2.0
 3.0  4.0

[:, :, 2] =
 10.0  20.0
 30.0  40.0

julia> print(typeof(A))
Array{Float32,3}

The '.' operator for broadcasting the operation element-wise.

Upvotes: 7

Bill
Bill

Reputation: 6086


    julia> x = zeros(3,3,3)
    3×3×3 Array{Float64,3}:
    [:, :, 1] =
     0.0  0.0  0.0
     0.0  0.0  0.0
     0.0  0.0  0.0

    [:, :, 2] =
     0.0  0.0  0.0
     0.0  0.0  0.0
     0.0  0.0  0.0

    [:, :, 3] =
     0.0  0.0  0.0
     0.0  0.0  0.0
     0.0  0.0  0.0

    julia> x .|> Float32
    3×3×3 Array{Float32,3}:
    [:, :, 1] =
     0.0  0.0  0.0
     0.0  0.0  0.0
     0.0  0.0  0.0

    [:, :, 2] =
     0.0  0.0  0.0
     0.0  0.0  0.0
     0.0  0.0  0.0

    [:, :, 3] =
     0.0  0.0  0.0
     0.0  0.0  0.0
     0.0  0.0  0.0

Upvotes: 0

Related Questions