MATLAB: Can I supply a gradient to fmincon when the objective function is anonymous

fmincon

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

Best Answer

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.