Basic solve with Optim/ NLsolve

I have a very simple problem, but a little stomped. Below is a MWE

using NLsolve
f! = function (dx, x, a, b) # we want to find roots for f
    dx[1] = x[1] - a[1]
    dx[2] = x[2] = a[2]
    b = 5
end
a = [1; 5]
b = 0
g!(dx, x) = f!(dx, x, a, b)
res = nlsolve(g!, [1.0; 1.0])

How do I return an updated ‘b’ from the above f! function.
Thanks in advance!

1 Like

You need to use something other than an Int:

julia> function foo(b::Int)
           b = 3
           return
       end
foo (generic function with 1 method)

julia> function bar(b::Ref{Int})
           b[] = 3
           return
       end
bar (generic function with 1 method)

julia> b = 2
2

julia> foo(b)

julia> c = Ref(2)
Base.RefValue{Int64}(2)

julia> bar(c)

julia> c[]
3

But I don’t know if your f! function makes sense. It overwrites x[2] to the constant a[2].

Even if you update b, the final value will be whatever was last calculated. There’s no guarantee this will correspond to a root (even if it probably will).

1 Like