Julia-数组的绝对值

时间:2018-12-27 10:29:27

标签: math julia linear-algebra absolute-value

我想获取以下数组的绝对值:

x = [1.1 -22.3 3.01, -1]

即:我想要一个类型为x2 = [1.1 22.3 3.01 1]的输出 但是当我键入:

abs(x)

我收到一个错误:

ERROR: MethodError: no method matching abs(::Array{Float64,2})
Closest candidates are:
  abs(::Pkg.Resolve.MaxSum.FieldValues.FieldValue) at /Users/vagrant/worker/juliapro-release-osx1011-0_6/build/tmp_julia/Julia-1.0.app/Contents/Resources/julia/share/julia/stdlib/v1.0/Pkg/src/resolve/FieldValues.jl:67
  abs(::Pkg.Resolve.VersionWeights.VersionWeight) at /Users/vagrant/worker/juliapro-release-osx1011-0_6/build/tmp_julia/Julia-1.0.app/Contents/Resources/julia/share/julia/stdlib/v1.0/Pkg/src/resolve/VersionWeights.jl:40
  abs(::Missing) at missing.jl:79
  ...
Stacktrace:
 [1] top-level scope at none:0

1 个答案:

答案 0 :(得分:7)

Julia不会自动将标量函数(例如abs)应用于数组的元素。相反,您应该告诉Julia这是您想要的,然后在数组上广播标量函数abs,请参见https://docs.julialang.org/en/v1/manual/arrays/#Broadcasting-1。可以这样做

julia> x = [1.1, -22.3, 3.01, -1];

julia> broadcast(abs, x)
4-element Array{Float64,1}:
  1.1 
 22.3 
  3.01
  1.0

或者您可以使用“点符号”,它更具意识形态:

julia> abs.(x)
4-element Array{Float64,1}:
  1.1 
 22.3 
  3.01
  1.0