Reputation: 264
I am completing maximum likelihood estimation inside a for loop.
When I don't converge, I get this error message,
error in objective function of fmincon and solver stopped prematurely
I have solved this with this answer: https://uk.mathworks.com/matlabcentral/answers/131975-error-in-objective-function-of-fmincon-and-solver-stopped-prematurely
However,
on certain occasions, I still can't converge.
Is it possible to count (automatically) how many times I don't converge?
Upvotes: 2
Views: 518
Reputation: 10792
You can use the exitflag
output of the fmincon
function:
[x,~,exitflag] = fmincon(fun,x0,A,b);
exitflag
indicate the reason why fmincon stopped.
According to the documentation exitflag
can take the following value:
All Algorithms:
1 %First-order optimality measure was less than options.OptimalityTolerance, and maximum constraint violation was less than options.ConstraintTolerance.
0 %Number of iterations exceeded options.MaxIterations or number of function evaluations exceeded options.MaxFunctionEvaluations.
-1 %Stopped by an output function or plot function.
-2 %No feasible point was found.
All algorithms except active-set:
2 %Change in x was less than options.StepTolerance and maximum constraint violation was less than options.ConstraintTolerance.
trust-region-reflective algorithm only:
3 %Change in the objective function value was less than options.FunctionTolerance and maximum constraint violation was less than options.ConstraintTolerance.
active-set algorithm only:
4 %Magnitude of the search direction was less than 2*options.StepTolerance and maximum constraint violation was less than options.ConstraintTolerance.
5 %Magnitude of directional derivative in search direction was less than 2*options.OptimalityTolerance and maximum constraint violation was less than options.ConstraintTolerance.
interior-point, sqp-legacy, and sqp algorithms:
-3 %Objective function at current iteration went below options.ObjectiveLimit and maximum constraint violation was less than options.ConstraintTolerance.
If fmincon sucessfully determine a minimum then exitflag == 1
.
So you can simply count how many time exitflag ~= 1
error_counter = 0;
for ii = 1:n_iteration
[x,~,exitflag] = fmincon(fun,x0,A,b);
if exitflag ~= 1
error_counter = error_counter + 1
end
end
And if you only want to check that the number of iterations has not been exceeded then you can replace exitflag ~= 1
with exitflag == 0
.
Upvotes: 4