MATLAB: Error “Too many output” using fmincon with supplied gradient

fmincongradient

I wish to optimize the function floglikelihood3(y,X,Z,p1,q1,p2,theta) with respect to theta (7×1 vector of parameters). The function returns two outputs, function value and gradient when two outputs are requested
[f g] = floglikelihood3(y,X,Z,p1,q1,p2,theta_mle)
f = -423.18
g = -74807
-0.71931
-76878
-0.72
-43.938
2.894e+05
-0.68371
and otherwise just the function output
[f ] = floglikelihood3(y,X,Z,p1,q1,p2,theta_mle)
f = -423.18
Using fmincon I encounter an error:
options = optimoptions('fmincon','GradObj','on');
[theta_mle2,Neglogl_unrestricted2,~,~,~,~,~] = fmincon(@(theta) -floglikelihood3(y,X,Z,p1,q1,p2,theta),theta_mle,[],[],[],[],lb,ub,[],options);
Error using -
Too many output arguments.
Error in fMaximizer>@(theta)-floglikelihood3(y,X,Z,p1,q1,p2,theta)
Error in fmincon (line 543)
[initVals.f,initVals.g] = feval(funfcn{3},X,varargin{:});
Caused by:
Failure in initial user-supplied objective function evaluation. FMINCON cannot continue.
I cant really understand why this error occurs?

Best Answer

You need to do the negation inside your function. You are returning the value of the function and have the - in front of that value to get its negative, which is throwing away the second output of the function because that's what happens when you have a function with two outputs whose value is being passed to another function. Then the negation function is being asked to supply two outputs and cannot.