Parametrize NLsolve function

Hello,
I want to solve a function using NLsolve, which has parameters. I do not want to pass them using global variables.

Simplified example:

using NLsolve
function f!(F, x)
    global a, b
    F[1] = a * sin(x[1]) + b
end
a = 1.0
b = 0.5
nlsolve(f!, [ 0.])

How can I solve this problem without using global variables?

1 Like
function f!(F,x,a,b)
   F[1] = a * sin(x[1]) + b
 end 
a = 1.0
b = 0.5 
nlsolve((F,x) ->f!(F,x,a,b), [ 0.])

Should do the trick.

4 Likes

Thanks! This works nicely. :slight_smile:

Hi, thanks for the reply on thi. Could you please comment on what does it mean the construction (F,x) ->f!(F,x,a,b) ?

And, more important, could you prove a link to any references to understand this concept in depth ? Thanks in advance !

The -> syntax creates an anonymous function: https://docs.julialang.org/en/v1/manual/functions/#man-anonymous-functions-1

foo = x -> 2 * x

is equivalent to

function foo(x)
    return 2 * x
end
2 Likes