# Looking for solvers like Matlab's fsolve for Julia

I am looking for a tutorial/package for a solver in Julia that is similar to fsolve in Matlab. My problem is mostly that I have a system of equations that I want to find a solution for. My system of equation however takes a vector of variables are given, which need to be included but are not to be solved for.

Thank you very much!

2 Likes

NLsolve.jl

You can use a closure for parameters. `my_closure = (t,u) -> f(t,u,2.0)` encloses `2.0`. Anonymous functions are fast in Julia so this is fine.

3 Likes

This is solved with a closure. If you have a function `f(x,p)` where `p` is a parameter you can easily create a new function `f2(x) = f2(x, p)` which â€ścloses overâ€ť `p`. See Documentation - Stack Overflow, https://docs.julialang.org/en/stable/devdocs/functions/#closures.

3 Likes

Thanks a lot

For anyone that is interested in a minimal example, although of course you donâ€™t need NLsolve to solve those equations

``````using NLsolve
f! = function (x,dx,a) # we want to find roots for f
dx[1] = x[1] - a[1]
dx[2] = x[2] - a[2]
end
a = [1;5]
g!(x,dx) = f!(x,dx,a) # g is our closure for a specific a

res = nlsolve(g!,[1.0;1.0])
res.zero # should give out [1;5] as the solution
``````
5 Likes

Never saw this syntax for defining generic functions before. Itâ€™s interesting

1 Like

Itâ€™s not actually a generic function (since you canâ€™t easily define other methods), itâ€™s just an anonymous function bound to a variable.

1 Like

Note that with NLsolveâ€™s newest version the input should be flipped so that way itâ€™s `(dx,x)`.

2 Likes

Oh yeah thatâ€™s true, itâ€™s an anonymous function. Makes more sense, syntax wise. Got confused at first because the output said â€ś(::#1) (generic function with 1 method)â€ť

I should have been more careful: the machinery underlying generic and anonymous functions is the same. The main practical difference is that generic functions give a `const` binding, which allows you to add more methods, e.g. a regular binding gives:

``````julia> f = x -> x+1
(::#1) (generic function with 1 method)

julia> f(x,y) = 2
ERROR: cannot define function f; it already has a value
``````

But if you make it `const`:

``````julia> const f = x -> x+1
(::#1) (generic function with 1 method)

julia> f(x,y) = 2
(::#1) (generic function with 2 methods)
``````

The only remaining difference between this and the usual definition is the lack of a function name (which is really only for user convenience).