# 带梯度的非线性约束

### 目标函数和非线性约束

`$\underset{x}{\mathrm{min}}f\left(x\right)={e}^{{x}_{1}}\left(4{x}_{1}^{2}+2{x}_{2}^{2}+4{x}_{1}{x}_{2}+2{x}_{2}+1\right),$`

`$\begin{array}{l}{x}_{1}{x}_{2}-{x}_{1}-{x}_{2}\le -1.5\\ {x}_{1}{x}_{2}\ge -10.\end{array}$`

$\mathit{c}\left(\mathit{x}\right)=\left[\begin{array}{c}{\mathit{x}}_{1}{\mathit{x}}_{2}-{\mathit{x}}_{1}-{\mathit{x}}_{2}+1.5\\ -10-{\mathit{x}}_{1}{\mathit{x}}_{2}\end{array}\right]$.

### 带梯度的目标函数

$f\left(x\right)={e}^{{x}_{1}}\left(4{x}_{1}^{2}+2{x}_{2}^{2}+4{x}_{1}{x}_{2}+2{x}_{2}+1\right)$.

$\nabla \mathit{f}\left(\mathit{x}\right)=\left[\begin{array}{c}\mathit{f}\left(\mathit{x}\right)+\mathrm{exp}\left({\mathit{x}}_{1}\right)\left(8{\mathit{x}}_{1}+4{\mathit{x}}_{2}\right)\\ \mathrm{exp}\left({\mathit{x}}_{1}\right)\left(4{\mathit{x}}_{1}+4{\mathit{x}}_{2}+2\right)\end{array}\right]$.

`fun = @objfungrad;`

### 带梯度的约束函数

`$\left[\begin{array}{cc}\frac{\partial {c}_{1}}{\partial {x}_{1}}& \frac{\partial {c}_{2}}{\partial {x}_{1}}\\ \frac{\partial {c}_{1}}{\partial {x}_{2}}& \frac{\partial {c}_{2}}{\partial {x}_{2}}\end{array}\right]=\left[\begin{array}{cc}{x}_{2}-1& -{x}_{2}\\ {x}_{1}-1& -{x}_{1}\end{array}\right].$`

`@confungrad` 设置为非线性约束函数。

`nonlcon = @confungrad;`

### 设置选项以使用导数信息

`fmincon` 求解器指示目标函数和约束函数提供导数信息。为此，请使用 `optimoptions``SpecifyObjectiveGradient``SpecifyConstraintGradient` 选项值设置为 `true`

```options = optimoptions('fmincon',... 'SpecifyObjectiveGradient',true,'SpecifyConstraintGradient',true);```

### 求解问题

`x0 = [-1,1];`

```A = []; b = []; Aeq = []; beq = []; lb = []; ub = [];```

`[x,fval] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options)`
```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. ```
```x = 1×2 -9.5473 1.0474 ```
```fval = 0.0236 ```

### 辅助函数

```function [f,gradf] = objfungrad(x) f = exp(x(1))*(4*x(1)^2+2*x(2)^2+4*x(1)*x(2)+2*x(2)+1); % Gradient of the objective function: if nargout > 1 gradf = [ f + exp(x(1)) * (8*x(1) + 4*x(2)), exp(x(1))*(4*x(1)+4*x(2)+2)]; end end```

```function [c,ceq,DC,DCeq] = confungrad(x) c(1) = 1.5 + x(1) * x(2) - x(1) - x(2); % Inequality constraints c(2) = -x(1) * x(2)-10; % No nonlinear equality constraints ceq=[]; % Gradient of the constraints: if nargout > 2 DC= [x(2)-1, -x(2); x(1)-1, -x(1)]; DCeq = []; end end```