Can I supply a gradient to fmincon when my objective function is anonymous?
5 views (last 30 days)
Show older comments
I am using fmincon and would like to supply a gradient for the objective function to speed up convergence. The trouble is I use an anonymous objective function so I can pass parameters to my real objective function. I believe the anonymous function only picks up the first argument of my real objective function, which is the function value and not the gradient. The basic structure of my code is:
if true
%%%%%%%%%%%%%%%%%%%
[f,gradf]=realobjective(parameters,x]
f=blah;
gradf=blah;
end
%%%%%%%%%%%%%%%%%%%
options=optimoptions(@fmincon,'Algorithm','active-set','MaxFunEvals',1E5,'MaxIter',1E5,'TolFun',1E-6,'TolX',1E-6,'GradConstr','on','GradObj','on');
xguess=0;
func=@(x)realobjective(parameters,x)
argmin=fmincon(func,xguess,[],[],[],[],0,1000,nonlconstr,options)
end
So I think fmincon is not using the gradient I have defined in the real objective function. I'd be incredibly grateful for any advice.
David
1 Comment
Rustem Devletov
on 26 Apr 2019
Hey, friend! I'm a fourth year student in Russia, currently writing my thesis. My supervisor asked me to provide gradient to fmincon
I have triend smth like this
function F = rosenbrockwithgrad(x)
F = 100*(x(2) - x(1)^2)^2 + (1-x(1))^2;
if nargout > 1 % gradient required
g = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1));
200*(x(2)-x(1)^2)];
end
But he said that he wants it to be found in another file. How can I implement this? How do I find gradient in one file and pass it to another one?
Accepted Answer
Matt J
on 13 Aug 2014
Edited: Matt J
on 13 Aug 2014
What you've posted looks fine. Call nargout inside realobjective (e.g., at a breakpoint), to test whether fmincon is calling it with two output arguments.
5 Comments
Matt J
on 13 Aug 2014
Did you try running with 'DerivativeCheck' set to 'on' to validate your gradient calculation? Sounds like your constraint gradient calculation is working okay, but the objective function gradient calculation might have errors.
Rustem Devletov
on 26 Apr 2019
Hey, friend! I'm a fourth year student in Russia, currently writing my thesis. My supervisor asked me to provide gradient to fmincon
I have triend smth like this
function F = rosenbrockwithgrad(x)
F = 100*(x(2) - x(1)^2)^2 + (1-x(1))^2;
if nargout > 1 % gradient required
g = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1));
200*(x(2)-x(1)^2)];
end
But he said that he wants it to be found in another file. How can I implement this? How do I find gradient in one file and pass it to another one?
More Answers (1)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!