MATLAB: Does the FMINCON function in the Optimization Toolbox 3.0.2 (R14SP2) return the wrong number of function evaluations when the “GradObj” option is set to “on”

# gradobjerrorfminconincorrectnonlconOptimization Toolbox

I create the following objective function that counts the number of times it has been called:
function [f,g,cout]=sumsquared(p)
persistent myCount
f=sum(p.^2);
if isempty(myCount)
myCount = 1;
else
myCount = myCount + 1;
end
if nargout>1, g=2*p; end % gradient computation

if nargout>2, cout=myCount; end % gradient computation
When I then execute the following commands:
opts=optimset('largescale','off','gradobj','on','display','none');
clear('sumsquared')
[x,fval,exitflag,output]=fmincon(@sumsquared,rand(40,1),eye(40),ones(40,1),...
[],[],[],[],[], opts);
[ignore ignore cout] = sumsquared([]);
ActualFunCount = cout-1
ReportedFunCount = output.funcCount
I find the actual number of function evaluations is fewer than that reported by the output of FMINCON:
ActualFunCount =
5
ReportedFunCount =
125

Best Answer

This bug has been fixed in Release 14 Service Pack 3 (R14SP3). For previous product releases, read below for any possible workarounds:
There is a bug in the FMINCON function in Optimization Toolbox 3.0.2 (R14SP2). It reports an incorrect number of function evaluations when the "GradObj" property is "on" and the non-linear constraint input "nonlcon" is empty.
There are no workarounds.