Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call NLopt with vectors #207

Closed
aloispichler opened this issue Oct 19, 2023 · 1 comment
Closed

Call NLopt with vectors #207

aloispichler opened this issue Oct 19, 2023 · 1 comment

Comments

@aloispichler
Copy link

aloispichler commented Oct 19, 2023

I am struggling with NLopt.jl. The following, simple objective is called with initial value [1,1,1,1], this value never changes, and the algorithm will not find the solution [0,0,0,0].
Any help is highly appreciated and thanks in advance.

using NLopt

function fun(Y::Vector, grad::Vector)::Float64
	if length(grad) > 0
		grad= 2*Y
	end
	@show "objective", length(grad), Y
	return Y'*Y
end

opt= Opt(:LD_MMA, 4)
opt.maxeval= 10

opt.max_objective= fun
(minf,minx,ret)= optimize(opt, ones(4))
numevals= opt.numevals
println("got $minf at $minx after $numevals iterations (returned $ret)")
@odow
Copy link
Member

odow commented Jan 15, 2024

You need to edit the grad vector in-place.

function fun(Y::Vector, grad::Vector)::Float64
   if length(grad) > 0
       grad .= 2*Y  #  Note `.=` not `=`
   end
   @show "objective", length(grad), Y
   return Y'*Y
end

Please post on the Julia discourse forum if you have other questions: https://discourse.julialang.org/c/domain/opt/13

@odow odow closed this as completed Jan 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants