Clear Filters
Clear Filters

Provide gradient for Fmincon

30 views (last 30 days)
Dat Tran
Dat Tran on 16 Feb 2016
Answered: Walter Roberson on 16 Feb 2016
Dear all,
How can I include Gradient for Objective Function in code below?
Thank you so much for your help!
Dat
function [p,fval] = MC_NT(p0,Aeq,beq,N)
if nargin < 5
opts = optimoptions('fmincon','Algorithm','interior-point');
end
M=length(p0);
pr1=[0.3185 0.0001 0.1574 0.2902 0.0003 0.00001 0.8426 0.7098 0.6804 0.0822 0.00001 0.00001 0.0008 0.9177 0.00001 0.00001];
pr=horzcat(pr1,(0.25*ones(48,1)'))';
p=nan(M,N);
fval=nan(1,N);
for i=1:N
fun=@(p) sum(p.*log(p./pr));
[p(:,i),fval(i)] = fmincon(fun,p0,[],[],Aeq,beq,[],[],[],opts);
pr=p(:,i);
end

Answers (1)

Walter Roberson
Walter Roberson on 16 Feb 2016
You would have to recode fun as a real function instead of anonymous function, as it is difficult for an anonymous function to return multiple outputs.
The function you provide would need to return the gradient in the second output.
You would need to specify the 'GradObj', 'on' option in your optimoptions()
There is an example showing a gradient calculation at http://www.mathworks.com/help/optim/ug/fmincon.html#busxd7j-1
As you have linear equality constraints but no bounds constraints and no non-linear constraints, you would have the option of switching to trust-region-reflective algorithm once you provide the gradient.

Categories

Find more on Systems of Nonlinear Equations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!