Вы можете использовать вывод exitflag
функции fmincon
:
[x,~,exitflag] = fmincon(fun,x0,A,b);
exitflag
указать причину остановки fmincon.
Согласно документации exitflag
может принимать следующее значение:
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.
Если fmincon успешно определит минимум, тогда exitflag == 1
. Таким образом, вы можете просто посчитать, сколько раз 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
И если вы хотите только проверить, что число итераций не превышено, вы можете заменить exitflag ~= 1
на exitflag == 0
.