Julia NLsolve gives DimensionMismatch-Error when dimension of codomain is larger than dimension of domain

Viewed 93
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?

1 Answers

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")
Related