MATLAB: Fminunc: Too many output arguments

fminunctoo many output arguments

Hi all, I can't find my bug in the following call of fminunc. The relevant section of my main file looks like this:
global W obs log_share price cost_shifter1 cost_shifter2 cost_shifter3 product_attrib1 product_attrib2 product_attrib3
opts = optimset('display','iter-detailed','Diagnostics','on','TolFun',1e-10,'TolX',1e-10,'GradObj','on','DerivativeCheck','off','Hessian','user-supplied');
start = beta_2SLS;
iter=1;
maxiter=2;
W=eye(6);
while iter<=maxiter
[betahat, fval] = fminunc(@(beta) moments(beta),start,opts);
W = varcov(betahat);
iter=iter+1;
end
That is, I call fminunc to minimize the function moments specified here:
function distance=moments(beta)
global W obs log_share price cost_shifter1 cost_shifter2 cost_shifter3 product_attrib1 product_attrib2 product_attrib3
residual1=zeros(obs,1);
for i_obs=1:obs
residual1(i_obs) = log_share(i_obs) - beta(1)-beta(2)*price(i_obs)- ...
[beta(3), beta(4), beta(5)]*[product_attrib1(i_obs); product_attrib2(i_obs); product_attrib3(i_obs)];
end
moment=(1/obs)*residual1'*[cost_shifter1, cost_shifter2, cost_shifter3, product_attrib1, product_attrib2, product_attrib3];
% ( 1 X 6) vector
distance = moment*W*moment';
end
When I run the section main file, I get the error message: Error using moments Too many output arguments.
Error in @(beta)moments(beta)
Error in fminunc (line 285) [f,GRAD,HESS] = feval(funfcn{3},x,varargin{:});
Caused by: Failure in initial objective function evaluation. FMINUNC cannot continue
Does anybody see my error or give me a hint, how to debug this? Thanks a lot.

Best Answer

In your options you set GradObj to 'on' and Hessian to 'user-supplied'. Yet your objective function does not return the gradient and Hessian of your objective function. For details on how to supply these, see Including Gradients and Hessian. If you have a Symbolic Math Toolbox™ license, you can calculate these quantities automatically, rather than doing it by hand; see Using Symbolic Math with Optimization Toolbox Solvers.
Good luck,
Alan Weiss
MATLAB mathematical toolbox documentation