How to exit an optimization function without error?

조회 수: 2 (최근 30일)
Sargondjani
Sargondjani 2023년 11월 6일
댓글: Sam Chak 2023년 11월 6일
I am using fsolve at two stages: first it finds the solution for problem A, and this solution is then used to solve problem B.
Sometimes it cannot find a solution for problem A, and then for sure i can not solve problem B, so I want fsolve (for B) to exit whenever problem A returns an exitflag < 1. How do I do this?
So far I only found that you can have the objective return an "inf" but then it will still try to backtrack, and waste time and resources. I would prefer to have something like:
if somecondition
exit fsolve
end

답변 (1개)

Sam Chak
Sam Chak 2023년 11월 6일
편집: Sam Chak 2023년 11월 6일
Can use return.
Update: Editted the solution by using the function approach.
%% Solving Stage A Problem first
fun1 = @problem1;
x0 = 1;
[xsol1, fval, exitflag] = fminsearch(fun1, x0)
Exiting: Maximum number of function evaluations has been exceeded - increase MaxFunEvals option. Current function value: -4017345110647497376329610801883911649791527634988546654208.000000
xsol1 = 6.3383e+28
fval = -4.0173e+57
exitflag = 0
%% Test if the solution from Stage A is admissible
if exitflag <= 0
warning('Terminated due Stage A problem is infeasible.')
return % stop if condition is satisfied
else
%% Solving Stage B Problem then
fun2 = @(x) problem2(x, xsol1);
x0 = 1;
xsol2 = fsolve(fun2, x0)
end
Warning: Terminated due Stage A problem is infeasible.
%% Stage A Problem
function y = problem1(x)
y = - x.^2; % infeasible
% y = 1 - x.*exp(-x.^2); % feasible
end
%% Stage B Problem
function y = problem2(x, xsol) % cost function requires xsol from Stage A
y = x.^2 + 2*x + xsol;
end
  댓글 수: 7
Sargondjani
Sargondjani 2023년 11월 6일
but i need to solve x1 for every value of x2, meaning when x2 changes, so will x1. your approach does not allow for that.
Sam Chak
Sam Chak 2023년 11월 6일
Okay, I got it now. It's a coupled interdependent problem. Need some time to think.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by