Error plotting array with exponential operation

Viewed 29

I am new to Julia and I am trying to create a plot with the following:

    xi2 = range(0,sqrt(6),step=1e-3)
    collect(xi2)
    plot(xi2, 1-xi2^2/6, label="n = 0")

When I try this though, I have the error:

MethodError: no method matching ^(::StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}, ::Int64)
Closest candidates are:
  ^(::Union{AbstractChar, AbstractString}, ::Integer) at C:\Users\Acer\AppData\Local\Programs\Julia-1.7.0\share\julia\base\strings\basic.jl:721
  ^(::Rational, ::Integer) at C:\Users\Acer\AppData\Local\Programs\Julia-1.7.0\share\julia\base\rational.jl:475
  ^(::Complex{<:AbstractFloat}, ::Integer) at C:\Users\Acer\AppData\Local\Programs\Julia-1.7.0\share\julia\base\complex.jl:839
  ...

What am I missing here?

1 Answers

You want the elements of xi2 raised to the power of two, so you want element-wise operations using the dot operator:


julia> xi2 = range(0,sqrt(6),step=1e-3);

julia> plot(xi2, 1 .- xi2.^2/6, label="n = 0")

(The collect step was unnecessary, since most array operations can be performed on a range directly. And in case you did want to collect - i.e. allocate memory and make it a full array - you have to assign the result of collect to some variable. In your original code, the elements were being collected into an array, but then thrown away since the result wasn't assigned to anything.)

Tada!

Related