## 非线性约束

`$\begin{array}{c}\frac{{x}_{1}^{2}}{9}+\frac{{x}_{2}^{2}}{4}\le 1,\\ {x}_{2}\ge {x}_{1}^{2}-1.\end{array}$`

```function [c,ceq] = ellipseparabola(x) c(1) = (x(1)^2)/9 + (x(2)^2)/4 - 1; c(2) = x(1)^2 - x(2) - 1; ceq = []; end```
`ellipseparabola` 为非线性等式约束函数 `ceq` 返回空条目 `[]`。同样，需要将第二个不等式重写为 ≤ 0 形式。

`ellipseparabola` 约束条件下最小化 `exp(x(1) + 2*x(2))` 函数。

```fun = @(x)exp(x(1) + 2*x(2)); nonlcon = @ellipseparabola; x0 = [0 0]; A = []; % No other constraints b = []; Aeq = []; beq = []; lb = []; ub = []; x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon)```
```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 = -0.2500 -0.9375```

### 在约束函数中包含梯度

```function [c,ceq,gradc,gradceq] = ellipseparabola(x) c(1) = x(1)^2/9 + x(2)^2/4 - 1; c(2) = x(1)^2 - x(2) - 1; ceq = []; if nargout > 2 gradc = [2*x(1)/9, 2*x(1); ... x(2)/2, -1]; gradceq = []; end```

`gradc`i, j = [∂`c`(j)/∂xi]。

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

```[x,fval] = fmincon(@myobj,x0,A,b,Aeq,beq,lb,ub, ... @ellipseparabola,options)```

### 匿名非线性约束函数

`deal` 函数分配多个输出。例如，假设您有非线性不等式

`$\begin{array}{c}\frac{{x}_{1}^{2}}{9}+\frac{{x}_{2}^{2}}{4}\le 1,\\ {x}_{2}\ge {x}_{1}^{2}-1.\end{array}$`

${x}_{2}=\mathrm{tanh}\left({x}_{1}\right)$.

```c = @(x)[x(1)^2/9 + x(2)^2/4 - 1; x(1)^2 - x(2) - 1]; ceq = @(x)tanh(x(1)) - x(2); nonlinfcn = @(x)deal(c(x),ceq(x));```

```obj = @(x)cosh(x(1))+sinh(x(2)); opts = optimoptions(@fmincon,'Algorithm','sqp'); z = fmincon(obj,[0;0],[],[],[],[],[],[],nonlinfcn,opts)```
```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. ```
```z = 2×1 -0.6530 -0.5737 ```

`[cout,ceqout] = nonlinfcn(z)`
```cout = 2×1 -0.8704 0 ```
```ceqout = 0 ```

`z` 在约束容差 `ConstraintTolerance` 默认值 `1e-6` 范围内满足所有约束。

## 另请参阅

| | (Global Optimization Toolbox) | (Global Optimization Toolbox) | (Global Optimization Toolbox) | (Global Optimization Toolbox)