I Like to Code
I Like to Code

Reputation: 7251

Convert float 2-D array to integer 2-D array in Julia

I know that it is possible to convert a Float64 into an Int64 using the convert function. Unfortunately, it doesn't work when applying convert to a 2-D array.

julia> convert(Int64, 2.0)
2

julia> A = [1.0 2.0; 3.0 4.0]
2x2 Array{Float64,2}:
 1.0  2.0
 3.0  4.0

julia> convert(Int64, A)
ERROR: `convert` has no method matching convert(::Type{Int64}, ::Array{Float64,2
})
 in convert at base.jl:13

How do I convert a 2-D array of floats into a 2-D array of ints?

What I tried

I could do it using the following code, which is a little verbose but it works. I am hoping there is an easier way to do it though.

julia> A = [1.0 2.0; 3.0 4.0]
2x2 Array{Float64,2}:
 1.0  2.0
 3.0  4.0

julia> B = Array(Int64, 2, 2)
2x2 Array{Int64,2}:
 4596199964293150115  4592706631984861405
 4604419156384151675                    0

julia> for i = 1:2
           for j = 1:2
               B[i,j] = convert(Int64,A[i,j])
           end
       end

julia> B
2x2 Array{Int64,2}:
 1  2
 3  4

An answer that doesn't work for me

julia> A = [1.2 3.4; 5.6 7.8]
2x2 Array{Float64,2}:
 1.2  3.4
 5.6  7.8

julia> round(Int64, A)
ERROR: `round` has no method matching round(::Type{Int64}, ::Array{Float64,2})

Upvotes: 10

Views: 12884

Answers (3)

reschu
reschu

Reputation: 1105

This answer is for Julia v0.3. For newer versions, see answer of DSM

Use the int function:

julia> a = rand(2,2)
2x2 Array{Float64,2}:
0.145651  0.362497
0.879268  0.753001

julia> int(a)
2x2 Array{Int64,2}:
0  0
1  1

Upvotes: -3

DSM
DSM

Reputation: 353059

You can convert a 2x2 array of floats into a 2x2 array of ints very easily, after you decide how you want rounding to be handled:

julia> A = [1.0 -0.3; 3.9 4.5]
2x2 Array{Float64,2}:
 1.0  -0.3
 3.9   4.5

julia> round.(Int, A)
2x2 Array{Int64,2}:
 1  0
 4  4

julia> floor.(Int, A)
2x2 Array{Int64,2}:
 1  -1
 3   4

julia> trunc.(Int, A)
2x2 Array{Int64,2}:
 1  0
 3  4

julia> ceil.(Int, A)
2x2 Array{Int64,2}:
 1  0
 4  5

Upvotes: 19

Tom Breloff
Tom Breloff

Reputation: 1802

You can use map, which preserves the matrix dimensions, and does not depend on vectorized methods:

julia> x = rand(2,2)
2x2 Array{Float64,2}:
 0.279777  0.610333
 0.277234  0.947914

julia> map(y->round(Int,y), x)
2x2 Array{Int64,2}:
 0  1
 0  1

Upvotes: 4

Related Questions