UndefVarError although I have defined it in the function before using it

I’m quite new to Julia but i’ve been getting this error for a while. I created a toy scenario similar to this where I define a variable just before using it in a function and it works there. However, I get an UndefVarError while doing the same here.
I’m working on the following function in ChaosTools.jl.

function rescale!(integ::MinimalDiscreteIntegrator{true, Vector{S}}, a) where {S<:Vector}
    @.  du = integ.u[1] + (integ.u[2] - integ.u[1])/a
    set_state!(integ,du,2)
    # @. integ.u[2] = integ.u[1] + (integ.u[2] - integ.u[1])/a
    # u_modified!(integ, true)
end
Got exception outside of a @test
  UndefVarError: du not defined
  Stacktrace:
    [1] rescale!(integ::DynamicalSystemsBase.MinimalDiscreteIntegrator{true, Vector{Vector{Float64}}, 3, DynamicalSystemsBase.var"#27#28"{DynamicalSystemsBase.DiscreteDynamicalSystem{true, Vector{Float64}, 3, var"#g#8", Nothing, DynamicalSystemsBase.var"#6#12"{ForwardDiff.JacobianConfig{ForwardDiff.Tag{DynamicalSystemsBase.var"#5#11"{var"#g#8", Nothing, Int64}, Float64}, Float64, 3, Tuple{Vector{ForwardDiff.Dual{ForwardDiff.Tag{DynamicalSystemsBase.var"#5#11"{var"#g#8", Nothing, Int64}, Float64}, Float64, 3}}, Vector{ForwardDiff.Dual{ForwardDiff.Tag{DynamicalSystemsBase.var"#5#11"{var"#g#8", Nothing, Int64}, Float64}, Float64, 3}}}}, DynamicalSystemsBase.var"#5#11"{var"#g#8", Nothing, Int64}, Vector{Float64}}, Matrix{Float64}, true}, Int64}, Nothing}, a::Float64)
      @ ChaosTools e:\Master Thesis\ChaosTools\ChaosTools.jl\src\chaosdetection\lyapunovs.jl:339

I can run the function by simply doing this

    set_state!(integ,integ.u[1] + (integ.u[2] - integ.u[1])./a,2)

however that makes for messy code and I think that way should be working.
Thank you.

1 Like

Try du = @. ... instead of @. du = .... The reason is that @. x = y expands into x .= y, which means copy y to existing x.

3 Likes

Thanks man that worked :pray:. I spent almost a day trying to fix this. :weary:

Happy to help. When code involving macros in general acts strangely give @macroexpand a shot:

julia> @macroexpand @. du = some(stuff[going].on)
:(du .= some.((stuff[going]).on))
5 Likes