I L*_*ode 7 arrays floating-point integer julia
我知道可以将a Float64
转换为Int64
使用该convert
函数.不幸的是,它在应用于convert
二维阵列时不起作用.
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
Run Code Online (Sandbox Code Playgroud)
如何将2-D浮点数组转换为2-D整数数组?
我可以使用以下代码来完成它,这有点冗长,但它的工作原理.我希望有一个更简单的方法来做到这一点.
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
Run Code Online (Sandbox Code Playgroud)
_
_ _ _(_)_ | A fresh approach to technical computing
(_) | (_) (_) | Documentation: http://docs.julialang.org
_ _ _| |_ __ _ | Type "help()" for help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 0.3.10 (2015-06-24 13:54 UTC)
_/ |\__'_|_|_|\__'_| | Official http://julialang.org release
|__/ | x86_64-linux-gnu
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})
Run Code Online (Sandbox Code Playgroud)
DSM*_*DSM 16
在决定如何处理舍入后,可以非常轻松地将2x2浮点数组转换为2x2的整数数组:
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
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用 map,它保留矩阵维度,并且不依赖于矢量化方法:
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
Run Code Online (Sandbox Code Playgroud)
res*_*chu -3
这个答案适用于 Julia v0.3。对于较新的版本,请参阅DSM的答案
使用该int
功能:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6950 次 |
最近记录: |