8

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
ecjb
  • 5,169
  • 12
  • 43
  • 79
  • Are you expecting `abs` to return an array where all the elements are their absolute value? – George Dec 27 '18 at 10:33
  • Thank you for your comment @George. Yes! i want a result of the type `x2 = [1.1 22.3 3.01]`. I'll update the question in that sense – ecjb Dec 27 '18 at 10:36
  • Looking at the docs I guess `for i = 0:length(x) x[i] = abs(x[i]) end` would work? Or resizing a new `x2` and assigning to that using the same for loop. – George Dec 27 '18 at 10:44

1 Answers1

20

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
fredrikekre
  • 10,413
  • 1
  • 32
  • 47
  • 1
    The [`@.` macro](https://docs.julialang.org/en/v1/base/arrays/#Base.Broadcast.@__dot__) is very handy, especially for more more complex cases. `@. x2 = abs(x)` – ederag Dec 27 '18 at 20:46