supply gradient to fmincon
11 views (last 30 days)
Show older comments
I'm trying to use fmincon, but when I run it I get the following warning:
Warning: To use the default trust-region-reflective algorithm you must supply the gradient in the objective function and set the GradObj option to 'on'. FMINCON will use the active-set algorithm instead. For information on applicable algorithms, see Choosing the Algorithm in the documentation.
I've read the documentation and looked for examples but I can't seem to figure out HOW to supply the gradient. I've defined it with my objective function and used optimoptions to turn it on, but I still get the warning.
function [f,gradf] = objfun(x)
InputData=importdata('LED_Spectra.txt');
s=importdata('input_spectra.txt');
Wavelength=350:.5:850;
tempWave=InputData(:,1);
r=[];
for n=2:size(InputData,2)
data=spline(tempWave,InputData(:,n),Wavelength);
data(Wavelength < min(tempWave))=0;
data(Wavelength > max(tempWave))=0;
r=[r data'];
end
s=spline(s(:,1),s(:,2),Wavelength);
s=s';
f=sum((s-x(1)*r(:,1)-x(2)*r(:,2)-x(3)*r(:,3)-x(4)*r(:,4)-x(5)*r(:,5)).^2);
gradf=sum(-2*r'*(s-r(:,1)-r(:,2)-r(:,3)-r(:,4)-r(:,5)));
end
x0=[1 1 1 1 1];
options = optimoptions('fmincon','GradObj','on');
[x,fval]=fmincon('objfun',x0,[],[],[],[],[0 0 0 0 0],[100 100 100 100 100])
I have already solved this particular problem with lsqlin, but I'm going to need to solve more complex problems with fmincon or something similar, so I'm just practicing with this example to try to figure out how to use it. fmincon returns the correct results, but it runs far too slowly to be useful right now. I'm hoping that using the gradient will speed it up.
0 Comments
Accepted Answer
Alan Weiss
on 11 Jun 2014
You need to pass the options to fmincon:
[x,fval]=fmincon('objfun',x0,[],[],[],[],[0 0 0 0 0],[100 100 100 100 100],[],options)
You might also want to pass the objective as a function handle:
[x,fval]=fmincon(@objfun,x0,...
Alan Weiss
MATLAB mathematical toolbox documentation
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!