Reputation: 21
using NLsolve
function g!(G,x)
G .= [x[1]^2-x[2] for i in 1:3]
end
nlsolve(g!,[0.1, 0.1])
This code gives a DimensionMismatch("array could not be broadcast to match destination")
When I instead use G .= [x[1]^2-x[2] for i in 1:2]
I don't get the error. It seems like NLsolve wants th input to be the same size as the output. Is this a bug or am I doing something wrong?
Upvotes: 2
Views: 240
Reputation: 36
Note that the problem that you are trying to solve is a Nonlinear Least Squares Problem, not Nonlinear Equations. The main difference between them is you are allowed to have under-determined or over-determined systems in the former, which makes getting the size of your output vector tricky. I recommend going over https://docs.sciml.ai/NonlinearSolve/stable/tutorials/getting_started/, which describes the main differences and how to solve them.
Now, coming to your specific problem.
using NonlinearSolve
function g!(G, x, p) # Note that we need to pass a parameter p for NonlinearSolve.jl
G[1] = x[1]^2 - x[2]
G[2] = x[1]^2 - x[2]
G[3] = x[1]^2 - x[2]
return nothing
end
Now we will creat the function passing resid_prototype
as zeros(3) which tells NonlinearSolve.jl that the residual vector is of length 3
nlf = NonlinearFunction(g!; resid_prototype=zeros(3))
prob = NonlinearLeastSquaresProblem(nlf, [0.1, 0.1])
Finally solve it. solve
by default will choose a robust polyalgorithm, else you can also pass in a solver of your choice from https://docs.sciml.ai/NonlinearSolve/stable/solvers/nonlinear_least_squares_solvers/
solve(prob)
Upvotes: 0
Reputation: 13800
This isn't an NLsolve
issue, in a fresh Julia session:
julia> function g!(G,x)
G .= [x[1]^2-x[2] for i in 1:3]
end
g! (generic function with 1 method)
julia> g!([0.0, 0.0], [1.0, 1.0])
ERROR: DimensionMismatch("array could not be broadcast to match destination")
Here I am passing G
with length 2, and then create an array of length 3 on the right hand side. .=
then tries to write the values created on the right hand side into the left hand side array element-by-element, but the sizes of the arrays are incompatible. Even shorter, you are essentially doing:
julia> [0, 0] .= [1, 2, 3]
ERROR: DimensionMismatch("array could not be broadcast to match destination")
Upvotes: 0