Search code examples
mathjulialinear-algebraabsolute-value

Julia - absolute value of an array


I want to get the absolute value of the following array:

x = [1.1 -22.3 3.01, -1]

i.e.: I want an output of the type: x2 = [1.1 22.3 3.01 1] However when I type:

abs(x)

I get an error:

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

Solution

  • Julia does not automatically apply scalar functions, like abs, to elements of an array. You should instead tell Julia this is what you want, and broadcast the scalar function abs over your array, see https://docs.julialang.org/en/v1/manual/arrays/#Broadcasting-1. This can be done as

    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
    

    or you can use "dot-notation", which is more ideomatic:

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