下面以fmincon为例来演示怎么实现:
给你的cost function写个wrapper
function [y, F] = myfunc(x) % Objective y = mycost(x); % Analytical Jacobian % F = 2*x; % Numerical Jacobian delta = 1e-5; F = (mycost(x+delta) - mycost(x))/delta; end function y = mycost(x) y = x^2; end
然后在script里写
opt = optimoptions('fmincon'); opt.SpecifyObjectiveGradient = true; fmincon(@myfunc, 10, [],[],[],[],[],[],[], opt)
运算结果如下
>> myoptimizer Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the default value of the optimality tolerance, and constraints are satisfied to within the default value of the constraint tolerance. <stopping criteria details> ans = -4.9997e-06
你可以尝试uncomment我的analytical jacobian那部分来用解析的Jacobian, 但是估计你的问题里面解析的不好求,还是用数值的吧。
我估计ipopt的语法比较类似。应该可以如此实现。