# 基于问题求解有约束非线性优化

$f\left(x,y\right)={e}^{x}\left(4{x}^{2}+2{y}^{2}+4xy+2y-1\right).$

type objfunx
function f = objfunx(x,y)
f = exp(x).*(4*x.^2 + 2*y.^2 + 4*x.*y + 2*y - 1);
end

x = optimvar('x');
y = optimvar('y');

obj = objfunx(x,y);

prob = optimproblem('Objective',obj);

$\frac{xy}{2}+\left(x+2{\right)}^{2}+\frac{\left(y-2{\right)}^{2}}{2}\le 2.$

TiltEllipse = x.*y/2 + (x+2).^2 + (y-2).^2/2 <= 2;

prob.Constraints.constr = TiltEllipse;

x0.x = -3;
x0.y = 3;

show(prob)
OptimizationProblem :

Solve for:
x, y

minimize :
(exp(x) .* (((((4 .* x.^2) + (2 .* y.^2)) + ((4 .* x) .* y)) + (2 .* y)) - 1))

subject to constr:
((((x .* y) ./ 2) + (x + 2).^2) + ((y - 2).^2 ./ 2)) <= 2

[sol,fval] = solve(prob,x0)
Solving problem using fmincon.

Local minimum found that satisfies the constraints.

Optimization completed because the objective function is non-decreasing in
feasible directions, to within the value of the optimality tolerance,
and constraints are satisfied to within the value of the constraint tolerance.
sol = struct with fields:
x: -5.2813
y: 4.6815

fval = 0.3299

x0.x = -1;
x0.y = 1;
[sol2,fval2] = solve(prob,x0)
Solving problem using fmincon.

Feasible point with lower objective function value found, but optimality criteria not satisfied. See output.bestfeasible..

Local minimum found that satisfies the constraints.

Optimization completed because the objective function is non-decreasing in
feasible directions, to within the value of the optimality tolerance,
and constraints are satisfied to within the value of the constraint tolerance.
sol2 = struct with fields:
x: -0.8210
y: 0.6696

fval2 = 0.7626

f = @objfunx;
g = @(x,y) x.*y/2+(x+2).^2+(y-2).^2/2-2;
rnge = [-5.5 -0.25 -0.25 7];
fimplicit(g,'k-')
axis(rnge);
hold on
fcontour(f,rnge,'LevelList',logspace(-1,1))
plot(sol.x,sol.y,'ro','LineWidth',2)
plot(sol2.x,sol2.y,'ko','LineWidth',2)
legend('Constraint','f Contours','Global Solution','Local Solution','Location','northeast');
hold off

### 使用 fcn2optimexpr 转换目标函数

obj = fcn2optimexpr(@objfunx,x,y);

prob = optimproblem('Objective',obj);