How to solve non-linear system with input array?

Hi,

I want to find the roots of a system of non-linear equations like this one:

function f!(F::Vector{Float64},
            Δ::Vector{Float64},
            L::Int64,
            N::Int64,
            g::Float64,
            Γ::Float64,
            Z::AbstractMatrix{Float64})
    F[1:L] .= Z*Δ
    for i=1:L
        F[i] += g^2*N*(L-N)*Γ - 2Δ[i] + g*sum(Z[i, :])*Δ[i] - Δ[i]^2
    end
    F[L+1] = sum(Δ) + 2N
    return F
end

My problem is that I wanted to use NLsolve to solve this problem, but the function f! has an argument Z that is an array and, therefore, NLsolve can’t handle it. There seems to be an issue already filed about this but there has not been any response yet in some months.

Do you know what solver I could use to find the roots of my function?

Do you mean that your unknowns are the matrix Z, and NLsolve expects a vector? That is easy — you can simply use reshape to convert NLsolve’s vector into a matrix of the corresponding size or vice versa.

If Z is a fixed parameter, and not a variable that you are solving for, it is even easier — just use a closure to wrap the parameter in the function that you pass to NLsolve.

1 Like

Sorry! It’s the second one, F preallocates the output, Δ are the unknown variables, and the other arguments are fixed.

By closure do you mean something like this

function main()
    L = 10
    Z = randn(L, L)

    clos(F, Δ) = f!(F, Δ, L, Z)
end

and pass clos as the function to solve? Is it not going to affect performance that the function depends on variables outside it?

Yes, and no that doesn’t hurt performance in general. Closures are the standard way to pass additional parameters through a higher-order function.

1 Like

Great, it works, thanks!! :smiley: