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 :slight_smile:

For anyone that is interested in a minimal example, although of course you don’t need NLsolve to solve those equations :slight_smile:

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).