# solve

## 语法

``sol = solve(prob)``
``sol = solve(prob,x0)``
``sol = solve(prob,x0,ms)``
``sol = solve(___,Name,Value)``
``[sol,fval] = solve(___)``
``[sol,fval,exitflag,output,lambda] = solve(___)``

## 说明

``sol = solve(prob)` 求解优化问题或方程问题 `prob`。`

``sol = solve(prob,x0)` 从点或一组值 `x0` 开始求解 `prob`。`

``sol = solve(prob,x0,ms)` 使用 `ms` 多起点求解器求解问题 `prob`。使用此语法搜索到的解优于不使用 `ms` 参量时获得的解。`

``sol = solve(___,Name,Value)` 支持上述语法中的输入参量，且可使用一个或多个名称-值对组参量修正求解过程。`
``[sol,fval] = solve(___)` 还使用上述语法中的任何输入参量返回在解处的目标函数值。`

``[sol,fval,exitflag,output,lambda] = solve(___)` 还返回一个说明退出条件的退出标志和一个 `output` 结构体（其中包含关于求解过程的其他信息）；对于非整数优化问题，还返回一个拉格朗日乘数结构体。`

## 示例

```x = optimvar('x'); y = optimvar('y'); prob = optimproblem; prob.Objective = -x - y/3; prob.Constraints.cons1 = x + y <= 2; prob.Constraints.cons2 = x + y/4 <= 1; prob.Constraints.cons3 = x - y <= 2; prob.Constraints.cons4 = x/4 + y >= -1; prob.Constraints.cons5 = x + y >= 1; prob.Constraints.cons6 = -x + y <= 2; sol = solve(prob)```
```Solving problem using linprog. Optimal solution found. ```
```sol = struct with fields: x: 0.6667 y: 1.3333 ```

${x}^{2}+{y}^{2}\le 4$ 区域内，求在 MATLAB® 中包含的 `peaks` 函数的最小值。为此，我们需要创建优化变量 `x``y`

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

`peaks` 作为目标函数，创建一个优化问题。

`prob = optimproblem("Objective",peaks(x,y));`

`prob.Constraints = x^2 + y^2 <= 4;`

`x` 的初始点设置为 1，将 `y` 设置为 –1，并求解问题。

```x0.x = 1; x0.y = -1; sol = 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: 0.2283 y: -1.6255 ```

```convpeaks = fcn2optimexpr(@peaks,x,y); prob.Objective = convpeaks; sol2 = 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. ```
```sol2 = struct with fields: x: 0.2283 y: -1.6255 ```

```prob = optimproblem; x = optimvar('x',8,1,'LowerBound',0,'Type','integer');```

```Aeq = [22 13 26 33 21 3 14 26 39 16 22 28 26 30 23 24 18 14 29 27 30 38 26 26 41 26 28 36 18 38 16 26]; beq = [ 7872 10466 11322 12058]; cons = Aeq*x == beq; prob.Constraints.cons = cons;```

```f = [2 10 13 17 7 5 7 3]; prob.Objective = f*x;```

`[x1,fval1,exitflag1,output1] = solve(prob);`
```Solving problem using intlinprog. Running HiGHS 1.6.0: Copyright (c) 2023 HiGHS under MIT licence terms Presolving model 4 rows, 8 cols, 32 nonzeros 4 rows, 8 cols, 27 nonzeros Objective function is integral with scale 1 Solving MIP model with: 4 rows 8 cols (0 binary, 8 integer, 0 implied int., 0 continuous) 27 nonzeros Nodes | B&B Tree | Objective Bounds | Dynamic Constraints | Work Proc. InQueue | Leaves Expl. | BestBound BestSol Gap | Cuts InLp Confl. | LpIters Time 0 0 0 0.00% 0 inf inf 0 0 0 0 0.0s 0 0 0 0.00% 1554.047531 inf inf 0 0 4 4 0.0s T 20753 210 8189 98.04% 1783.696925 1854 3.79% 30 8 9884 19222 2.6s Solving report Status Optimal Primal bound 1854 Dual bound 1854 Gap 0% (tolerance: 0.01%) Solution status feasible 1854 (objective) 0 (bound viol.) 9.63673585375e-14 (int. viol.) 0 (row viol.) Timing 2.69 (total) 0.00 (presolve) 0.00 (postsolve) Nodes 21163 LP iterations 19608 (total) 223 (strong br.) 76 (separation) 1018 (heuristics) Optimal solution found. Intlinprog stopped because the objective value is within a gap tolerance of the optimal value, options.AbsoluteGapTolerance = 1e-06. The intcon variables are integer within tolerance, options.ConstraintTolerance = 1e-06. ```

```x0.x = [8 62 23 103 53 84 46 34]'; [x2,fval2,exitflag2,output2] = solve(prob,x0);```
```Solving problem using intlinprog. Running HiGHS 1.6.0: Copyright (c) 2023 HiGHS under MIT licence terms Solution has num max sum Col infeasibilities 0 0 0 Integer infeasibilities 0 0 0 Row infeasibilities 0 0 0 Row residuals 0 0 0 Presolving model 4 rows, 8 cols, 32 nonzeros 4 rows, 8 cols, 27 nonzeros MIP start solution is feasible, objective value is 3901 Objective function is integral with scale 1 Solving MIP model with: 4 rows 8 cols (0 binary, 8 integer, 0 implied int., 0 continuous) 27 nonzeros Nodes | B&B Tree | Objective Bounds | Dynamic Constraints | Work Proc. InQueue | Leaves Expl. | BestBound BestSol Gap | Cuts InLp Confl. | LpIters Time 0 0 0 0.00% 0 3901 100.00% 0 0 0 0 0.0s 0 0 0 0.00% 1554.047531 3901 60.16% 0 0 4 4 0.0s T 6266 708 2644 73.61% 1662.791423 3301 49.63% 20 6 9746 10699 1.5s T 9340 919 3970 80.72% 1692.410008 2687 37.01% 29 6 9995 16120 2.2s T 21750 192 9514 96.83% 1791.542628 1854 3.37% 20 6 9984 40278 5.0s Solving report Status Optimal Primal bound 1854 Dual bound 1854 Gap 0% (tolerance: 0.01%) Solution status feasible 1854 (objective) 0 (bound viol.) 1.42108547152e-13 (int. viol.) 0 (row viol.) Timing 5.11 (total) 0.01 (presolve) 0.00 (postsolve) Nodes 22163 LP iterations 40863 (total) 538 (strong br.) 64 (separation) 2782 (heuristics) Optimal solution found. Intlinprog stopped because the objective value is within a gap tolerance of the optimal value, options.AbsoluteGapTolerance = 1e-06. The intcon variables are integer within tolerance, options.ConstraintTolerance = 1e-06. ```
`fprintf('Without an initial point, solve took %d steps.\nWith an initial point, solve took %d steps.',output1.numnodes,output2.numnodes)`
```Without an initial point, solve took 21163 steps. With an initial point, solve took 22163 steps. ```

• `ga`

• `gamultiobj`

• `paretosearch`

• `surrogateopt`

• `paretosearch`

• `surrogateopt`

```x = optimvar("x",LowerBound=-10,UpperBound=10); y = optimvar("y",LowerBound=-5/2,UpperBound=5/2); prob = optimproblem("Objective",peaks(x,y)); xval = -10:10; yval = (-5:5)/2; [x0x,x0y] = meshgrid(xval,yval); peaksvals = peaks(x0x,x0y);```

```x0 = optimvalues(prob,'x',x0x(:)','y',x0y(:)',... "Objective",peaksvals(:)');```

`[sol,fval,eflag,output] = solve(prob,x0,Solver="surrogateopt")`
```Solving problem using surrogateopt. ```

```surrogateopt stopped because it exceeded the function evaluation limit set by 'options.MaxFunctionEvaluations'. ```
```sol = struct with fields: x: 0.2279 y: -1.6258 ```
```fval = -6.5511 ```
```eflag = SolverLimitExceeded ```
```output = struct with fields: elapsedtime: 17.7298 funccount: 200 constrviolation: 0 ineq: [1x1 struct] rngstate: [1x1 struct] message: 'surrogateopt stopped because it exceeded the function evaluation limit set by ...' solver: 'surrogateopt' ```

```x = optimvar("x",LowerBound=-5,UpperBound=5); y = optimvar("y",LowerBound=-5,UpperBound=5); x0.x = -1; x0.y = 2; prob = optimproblem(Objective=peaks(x,y)); opts = optimoptions("fmincon",Display="none"); [sol,fval] = solve(prob,x0,Options=opts)```
```sol = struct with fields: x: -3.3867 y: 3.6341 ```
```fval = 1.1224e-07 ```

```ms = GlobalSearch; [sol2,fval2] = solve(prob,x0,ms)```
```Solving problem using GlobalSearch. GlobalSearch stopped because it analyzed all the trial points. All 15 local solver runs converged with a positive local solver exit flag. ```
```sol2 = struct with fields: x: 0.2283 y: -1.6255 ```
```fval2 = -6.5511 ```

`GlobalSearch` 找到一个目标函数值更好（更低）的解。退出消息显示局部求解器 `fmincon` 运行了 15 次。返回的解的目标函数值约为 –6.5511，低于第一个解的值 1.1224e–07。

`$\underset{x}{\mathrm{min}}\left(-3{x}_{1}-2{x}_{2}-{x}_{3}\right)\phantom{\rule{0.2777777777777778em}{0ex}}subject\phantom{\rule{0.2777777777777778em}{0ex}}to\left\{\begin{array}{l}{x}_{3}\phantom{\rule{0.2777777777777778em}{0ex}}binary\\ {x}_{1},{x}_{2}\ge 0\\ {x}_{1}+{x}_{2}+{x}_{3}\le 7\\ 4{x}_{1}+2{x}_{2}+{x}_{3}=12\end{array}$`

```x = optimvar('x',2,1,'LowerBound',0); x3 = optimvar('x3','Type','integer','LowerBound',0,'UpperBound',1); prob = optimproblem; prob.Objective = -3*x(1) - 2*x(2) - x3; prob.Constraints.cons1 = x(1) + x(2) + x3 <= 7; prob.Constraints.cons2 = 4*x(1) + 2*x(2) + x3 == 12; options = optimoptions('intlinprog','Display','off'); sol = solve(prob,'Options',options)```
```sol = struct with fields: x: [2x1 double] x3: 0 ```

`sol.x`
```ans = 2×1 0 6 ```
`sol.x3`
```ans = 0 ```

```x = optimvar('x'); y = optimvar('y'); prob = optimproblem; prob.Objective = -x - y/3; prob.Constraints.cons1 = x + y <= 2; prob.Constraints.cons2 = x + y/4 <= 1; prob.Constraints.cons3 = x - y <= 2; prob.Constraints.cons4 = x/4 + y >= -1; prob.Constraints.cons5 = x + y >= 1; prob.Constraints.cons6 = -x + y <= 2; sol = solve(prob,'Solver', 'intlinprog')```
```Solving problem using intlinprog. Running HiGHS 1.6.0: Copyright (c) 2023 HiGHS under MIT licence terms Presolving model 6 rows, 2 cols, 12 nonzeros 4 rows, 2 cols, 8 nonzeros 4 rows, 2 cols, 8 nonzeros Presolve : Reductions: rows 4(-2); columns 2(-0); elements 8(-4) Solving the presolved LP Using EKK dual simplex solver - serial Iteration Objective Infeasibilities num(sum) 0 -1.3333333333e+03 Ph1: 3(4499); Du: 2(1.33333) 0s 3 -1.1111111111e+00 Pr: 0(0) 0s Solving the original LP from the solution after postsolve Model status : Optimal Simplex iterations: 3 Objective value : -1.1111111111e+00 HiGHS run time : 0.01 Optimal solution found. No integer variables specified. Intlinprog solved the linear problem. ```
```sol = struct with fields: x: 0.6667 y: 1.3333 ```

```x = optimvar('x',2,1,'LowerBound',0); x3 = optimvar('x3','Type','integer','LowerBound',0,'UpperBound',1); prob = optimproblem; prob.Objective = -3*x(1) - 2*x(2) - x3; prob.Constraints.cons1 = x(1) + x(2) + x3 <= 7; prob.Constraints.cons2 = 4*x(1) + 2*x(2) + x3 == 12; [sol,fval,exitflag,output] = solve(prob)```
```Solving problem using intlinprog. Running HiGHS 1.6.0: Copyright (c) 2023 HiGHS under MIT licence terms Presolving model 2 rows, 3 cols, 6 nonzeros 0 rows, 0 cols, 0 nonzeros Presolve: Optimal Solving report Status Optimal Primal bound -12 Dual bound -12 Gap 0% (tolerance: 0.01%) Solution status feasible -12 (objective) 0 (bound viol.) 0 (int. viol.) 0 (row viol.) Timing 0.00 (total) 0.00 (presolve) 0.00 (postsolve) Nodes 0 LP iterations 0 (total) 0 (strong br.) 0 (separation) 0 (heuristics) Optimal solution found. Intlinprog stopped at the root node because the objective value is within a gap tolerance of the optimal value, options.AbsoluteGapTolerance = 1e-06. The intcon variables are integer within tolerance, options.ConstraintTolerance = 1e-06. ```
```sol = struct with fields: x: [2x1 double] x3: 0 ```
```fval = -12 ```
```exitflag = OptimalSolution ```
```output = struct with fields: relativegap: 0 absolutegap: 0 numfeaspoints: [] numnodes: 0 constrviolation: 0 algorithm: 'highs' message: 'Optimal solution found....' solver: 'intlinprog' ```

```rng(0) % For reproducibility p = optimproblem('ObjectiveSense', 'maximize'); flow = optimvar('flow', ... {'apples', 'oranges', 'bananas', 'berries'}, {'NYC', 'BOS', 'LAX'}, ... 'LowerBound',0,'Type','integer'); p.Objective = sum(sum(rand(4,3).*flow)); p.Constraints.NYC = rand(1,4)*flow(:,'NYC') <= 10; p.Constraints.BOS = rand(1,4)*flow(:,'BOS') <= 12; p.Constraints.LAX = rand(1,4)*flow(:,'LAX') <= 35; sol = solve(p);```
```Solving problem using intlinprog. Running HiGHS 1.6.0: Copyright (c) 2023 HiGHS under MIT licence terms Presolving model 3 rows, 12 cols, 12 nonzeros 3 rows, 12 cols, 12 nonzeros Solving MIP model with: 3 rows 12 cols (0 binary, 12 integer, 0 implied int., 0 continuous) 12 nonzeros Nodes | B&B Tree | Objective Bounds | Dynamic Constraints | Work Proc. InQueue | Leaves Expl. | BestBound BestSol Gap | Cuts InLp Confl. | LpIters Time 0 0 0 0.00% 1160.150059 -inf inf 0 0 0 0 0.0s S 0 0 0 0.00% 1160.150059 1027.233133 12.94% 0 0 0 0 0.0s Solving report Status Optimal Primal bound 1027.23313332 Dual bound 1027.23313332 Gap 0% (tolerance: 0.01%) Solution status feasible 1027.23313332 (objective) 0 (bound viol.) 0 (int. viol.) 0 (row viol.) Timing 0.01 (total) 0.00 (presolve) 0.00 (postsolve) Nodes 1 LP iterations 3 (total) 0 (strong br.) 0 (separation) 0 (heuristics) Optimal solution found. Intlinprog stopped at the root node because the objective value is within a gap tolerance of the optimal value, options.AbsoluteGapTolerance = 1e-06. The intcon variables are integer within tolerance, options.ConstraintTolerance = 1e-06. ```

`[idxFruit,idxAirports] = findindex(flow, {'oranges','berries'}, {'NYC', 'LAX'})`
```idxFruit = 1×2 2 4 ```
```idxAirports = 1×2 1 3 ```
`orangeBerries = sol.flow(idxFruit, idxAirports)`
```orangeBerries = 2×2 0 980 70 0 ```

`Fruit Airports`

` ----- --------`

` Berries NYC`

` Apples BOS`

` Oranges LAX`

`idx = findindex(flow, {'berries', 'apples', 'oranges'}, {'NYC', 'BOS', 'LAX'})`
```idx = 1×3 4 5 10 ```
`optimalFlow = sol.flow(idx)`
```optimalFlow = 1×3 70 28 980 ```

`$\begin{array}{l}\mathrm{exp}\left(-\mathrm{exp}\left(-\left({x}_{1}+{x}_{2}\right)\right)\right)={x}_{2}\left(1+{x}_{1}^{2}\right)\\ {x}_{1}\mathrm{cos}\left({x}_{2}\right)+{x}_{2}\mathrm{sin}\left({x}_{1}\right)=\frac{1}{2}\end{array}$`

`x = optimvar('x',2);`

`eq1 = exp(-exp(-(x(1) + x(2)))) == x(2)*(1 + x(1)^2);`

`eq2 = x(1)*cos(x(2)) + x(2)*sin(x(1)) == 1/2;`

```prob = eqnproblem; prob.Equations.eq1 = eq1; prob.Equations.eq2 = eq2;```

`show(prob)`
``` EquationProblem : Solve for: x eq1: exp((-exp((-(x(1) + x(2)))))) == (x(2) .* (1 + x(1).^2)) eq2: ((x(1) .* cos(x(2))) + (x(2) .* sin(x(1)))) == 0.5 ```

`[0,0]` 点开始求解问题。对于基于问题的方法，将初始点指定为结构体，并将变量名称作为结构体的字段。对于此问题，只有一个变量，即 `x`

```x0.x = [0 0]; [sol,fval,exitflag] = solve(prob,x0)```
```Solving problem using fsolve. Equation solved. fsolve completed because the vector of function values is near zero as measured by the value of the function tolerance, and the problem appears regular as measured by the gradient. ```
```sol = struct with fields: x: [2x1 double] ```
```fval = struct with fields: eq1: -2.4070e-07 eq2: -3.8255e-08 ```
```exitflag = EquationSolved ```

`disp(sol.x)`
``` 0.3532 0.6061 ```

```ls1 = fcn2optimexpr(@(x)exp(-exp(-(x(1)+x(2)))),x); eq1 = ls1 == x(2)*(1 + x(1)^2); ls2 = fcn2optimexpr(@(x)x(1)*cos(x(2))+x(2)*sin(x(1)),x); eq2 = ls2 == 1/2;```

## 输入参数

### 名称-值参数

`MultiStart` (Global Optimization Toolbox) 的最小起点数，指定为正整数。仅当使用 `ms` 参量调用 `solve` 时，此参量才适用。`solve` 使用 `x0` 中的所有值作为起点。如果 `MinNumStartPoints` 大于 `x0` 中的值的数目，则 `solve` 会在问题边界内均匀且随机地生成更多起点。如果某个分量为无界，`solve` 使用 `MultiStart` 的默认人为边界生成这些点。

`fminunc` 用于没有约束的问题，否则使用 `fmincon`

LPMILPQPSOCP线性最小二乘非线性最小二乘NLPMINLP

`linprog`

xxxxxxx
`intlinprog`

xxxxxx
`quadprog`

x

xxx
`coneprog`

xx

xxxx
`lsqlin`xxxx

xxx
`lsqnonneg`xxxx

xxx
`lsqnonlin`xxxx

xx
`fminunc`

x

x

x
`fmincon`

x

x
`fminbnd`xxxx

x
`fminsearch`xxxx

x
`patternsearch` (Global Optimization Toolbox)

x

x
`ga` (Global Optimization Toolbox)

`particleswarm` (Global Optimization Toolbox)

x

x

x
`simulannealbnd` (Global Optimization Toolbox)

x

x

x
`surrogateopt` (Global Optimization Toolbox)

`gamultiobj` (Global Optimization Toolbox)

`paretosearch` (Global Optimization Toolbox)

x

x

• * 表示该问题类型的默认求解器。

• Y 表示可用的求解器。

• N 表示不可用的求解器。

• 对于一般的非线性目标函数，`fmincon` 默认选择反向 AD。对于非线性约束函数，如果其非线性约束的数量小于变量数目，`fmincon` 默认选择反向 AD。否则，`fmincon` 默认选择正向 AD。

• 对于一般的非线性目标函数，`fminunc` 默认选择反向 AD。

• 对于最小二乘目标函数，`fmincon``fminunc` 对目标函数默认选择正向 AD。有关基于问题的最小二乘目标函数的定义，请参阅Write Objective Function for Problem-Based Least Squares

• 当目标向量中的元素数大于或等于变量数时，`lsqnonlin` 默认选择正向 AD。否则，`lsqnonlin` 默认选择反向 AD。

• 当方程数大于或等于变量数时，`fsolve` 默认选择正向 AD。否则，`fsolve` 默认选择反向 AD。

• 对于一般的非线性目标函数，`fmincon` 默认选择反向 AD。对于非线性约束函数，如果其非线性约束的数量小于变量数目，`fmincon` 默认选择反向 AD。否则，`fmincon` 默认选择正向 AD。

• 对于一般的非线性目标函数，`fminunc` 默认选择反向 AD。

• 对于最小二乘目标函数，`fmincon``fminunc` 对目标函数默认选择正向 AD。有关基于问题的最小二乘目标函数的定义，请参阅Write Objective Function for Problem-Based Least Squares

• 当目标向量中的元素数大于或等于变量数时，`lsqnonlin` 默认选择正向 AD。否则，`lsqnonlin` 默认选择反向 AD。

• 当方程数大于或等于变量数时，`fsolve` 默认选择正向 AD。否则，`fsolve` 默认选择反向 AD。

• 对于一般的非线性目标函数，`fmincon` 默认选择反向 AD。对于非线性约束函数，如果其非线性约束的数量小于变量数目，`fmincon` 默认选择反向 AD。否则，`fmincon` 默认选择正向 AD。

• 对于一般的非线性目标函数，`fminunc` 默认选择反向 AD。

• 对于最小二乘目标函数，`fmincon``fminunc` 对目标函数默认选择正向 AD。有关基于问题的最小二乘目标函数的定义，请参阅Write Objective Function for Problem-Based Least Squares

• 当目标向量中的元素数大于或等于变量数时，`lsqnonlin` 默认选择正向 AD。否则，`lsqnonlin` 默认选择反向 AD。

• 当方程数大于或等于变量数时，`fsolve` 默认选择正向 AD。否则，`fsolve` 默认选择反向 AD。

## 输出参量

`fval = evaluate(prob.Objective,sol)`

`fval = evaluate(prob.Objective.ObjectiveName,sol)`

```fnames = fields(prob.Equations); for i = 1:length(fnames) fval.(fnames{i}) = evaluate(prob.Equations.(fnames{i}),sol); end```

`intlinprog` 的退出标志等效数值含义
`OptimalWithPoorFeasibility``3`

`IntegerFeasible`2`intlinprog` 过早停止，并找到一个整数可行点。
`OptimalSolution`

`1`

`SolverLimitExceeded`

`0`

`intlinprog` 超过以下容差之一：

• `LPMaxIterations`

• `MaxNodes`

• `MaxTime`

• `RootLPMaxIterations`

`OutputFcnStop``-1``intlinprog` 由输出函数或绘图函数停止。
`NoFeasiblePointFound`

`-2`

`Unbounded`

`-3`

`FeasibilityLost`

`-9`

`linprog` 的退出标志等效数值含义
`OptimalWithPoorFeasibility``3`

`OptimalSolution``1`

`SolverLimitExceeded``0`

`NoFeasiblePointFound``-2`

`Unbounded``-3`

`FoundNaN``-4`

`PrimalDualInfeasible``-5`

`DirectionTooSmall``-7`

`FeasibilityLost``-9`

`lsqlin` 的退出标志等效数值含义
`FunctionChangeBelowTolerance``3`

`StepSizeBelowTolerance`

`2`

`OptimalSolution``1`

`SolverLimitExceeded``0`

`NoFeasiblePointFound``-2`

`IllConditioned``-4`

`NoDescentDirectionFound``-8`

`quadprog` 的退出标志等效数值含义
`LocalMinimumFound``4`

`FunctionChangeBelowTolerance``3`

`StepSizeBelowTolerance`

`2`

`OptimalSolution``1`

`SolverLimitExceeded``0`

`NoFeasiblePointFound``-2`

`IllConditioned``-4`

`Nonconvex`

`-6`

`NoDescentDirectionFound``-8`

`coneprog` 的退出标志等效数值含义
`OptimalSolution``1`

`SolverLimitExceeded``0`

`NoFeasiblePointFound``-2`

`Unbounded``-3`

`DirectionTooSmall`

`-7`

`Unstable``-10`

`lsqnonlin` 的退出标志等效数值含义
`SearchDirectionTooSmall ``4`

`FunctionChangeBelowTolerance``3`

`StepSizeBelowTolerance`

`2`

`OptimalSolution``1`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`NoFeasiblePointFound``-2`

`fminunc` 的退出标志等效数值含义
`NoDecreaseAlongSearchDirection``5`

`FunctionChangeBelowTolerance``3`

`StepSizeBelowTolerance`

`2`

`x` 中的变化小于 `options.StepTolerance` 容差。

`OptimalSolution``1`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`Unbounded``-3`

`fmincon` 的退出标志等效数值含义
`NoDecreaseAlongSearchDirection``5`

`SearchDirectionTooSmall``4`

`FunctionChangeBelowTolerance``3`

`StepSizeBelowTolerance`

`2`

`x` 的变化小于 `options.StepTolerance`，最大约束违反值小于 `options.ConstraintTolerance`

`OptimalSolution``1`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`NoFeasiblePointFound``-2`

`Unbounded``-3`

`fsolve` 的退出标志等效数值含义
`SearchDirectionTooSmall``4`

`FunctionChangeBelowTolerance``3`

`StepSizeBelowTolerance`

`2`

`x` 中的变化小于 `options.StepTolerance`，方程已解。

`OptimalSolution``1`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`NoFeasiblePointFound``-2`

`TrustRegionRadiusTooSmall``-3`

`fzero` 的退出标志等效数值含义
`OptimalSolution``1`

`OutputFcnStop``-1`

`FoundNaNInfOrComplex``-4`

`SingularPoint``-5`

`CannotDetectSignChange``-6`找不到函数值的符号相反的两个点。

`patternsearch` 的退出标志等效数值含义
`SearchDirectionTooSmall``4`

`FunctionChangeBelowTolerance``3`

`fval` 中的变化和网格大小都小于指定的容差，并且约束违反值小于 `ConstraintTolerance`

`StepSizeBelowTolerance`

`2`

`x` 中的变化和网格大小都小于 `StepTolerance`，并且约束违反值小于 `ConstraintTolerance`

`SolverConvergedSuccessfully``1`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`NoFeasiblePointFound``-2`

`ga` 的退出标志等效数值含义
`MinimumFitnessLimitReached``5`

`SearchDirectionTooSmall``4`

`FunctionChangeBelowTolerance``3`

`SolverConvergedSuccessfully``1`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`NoFeasiblePointFound``-2`

`StallTimeLimitExceeded``-4`

`TimeLimitExceeded``-5`

`particleswarm` 的退出标志等效数值含义
`SolverConvergedSuccessfully``1`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`NoFeasiblePointFound``-2`

`Unbounded``-3`

`StallTimeLimitExceeded``-4`

`TimeLimitExceeded``-5`

`simulannealbnd` 的退出标志等效数值含义
`ObjectiveValueBelowLimit``5`

`SolverConvergedSuccessfully``1`

`options.MaxStallIterations` 次迭代中，目标函数值的平均变化小于 `options.FunctionTolerance`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`NoFeasiblePointFound``-2`

`TimeLimitExceeded``-5`

`surrogateopt` 的退出标志等效数值含义
`BoundsEqual``10`

• 所有上界 `ub` (Global Optimization Toolbox) 都等于下界 `lb` (Global Optimization Toolbox)

• 线性等式约束 `Aeq*x = beq` 和边界有唯一解点。

`surrogateopt` 返回可行点和函数值，而不执行任何优化。

`FeasiblePointFound``3`找到可行点。求解器停止，因为找到的新可行点太少，无法继续。
`ObjectiveLimitAttained``1`

`SolverLimitExceeded``0`

`OutputFcnStop``-1`

`NoFeasiblePointFound``-2`

• 下界 `lb(i)` 超过对应的上界 `ub(i)`。或者对于 `intcon` (Global Optimization Toolbox) 中 i，存在一个或多个 `ceil(lb(i))` 超过对应的 `floor(ub(i))`。在这种情况下，`solve` 返回 `x = []``fval = []`

• `lb = ub` 并且点 `lb` 不可行。在这种情况下，`x = lb``fval = objconstr(x).Fval`

• 线性约束和整数约束（如果存在）与边界一同存在时是不可行的。在这种情况下，`solve` 返回 `x = []``fval = []`

• 边界、整数和线性约束是可行的，但在非线性约束下找不到可行解。在这种情况下，`x` 是非线性约束下最小的最大不可行性点，并且 `fval = objconstr(x).Fval`

`MultiStart``GlobalSearch` 的退出标志等效数值含义
`LocalMinimumFoundSomeConverged``2`找到至少一个局部最小值。局部求解器的某些运行已收敛。
`LocalMinimumFoundAllConverged``1`找到至少一个局部最小值。局部求解器的所有运行都已收敛。
`SolverLimitExceeded``0`找不到局部最小值。至少调用了一次局部求解器，并且局部求解器调用超出迭代次数至少一次。
`OutputFcnStop``–1`由输出函数或绘图函数停止。
`NoFeasibleLocalMinimumFound``–2`找不到可行的局部最小值。
`TimeLimitExceeded``–5`超过 `MaxTime` 限制。
`NoSolutionFound``–8`找不到解。所有运行都有局部求解器退出标志 –2 或更小值，但不都等于 –2。
`FailureInSuppliedFcn``–10`在目标函数或非线性约束函数中遇到失败。

`paretosearch` 的退出标志等效数值含义
`SolverConvergedSuccessfully``1`

• 所有现任点的网格大小小于 `options.MeshTolerance`，并且约束（如果有）满足在 `options.ConstraintTolerance` 内。

• 帕累托集的间距的相对变化小于 `options.ParetoSetChangeTolerance`，并且约束（如果有）满足在 `options.ConstraintTolerance` 内。

• 帕累托集的体积的相对变化小于 `options.ParetoSetChangeTolerance`，并且约束（如果有）满足在 `options.ConstraintTolerance` 内。

`SolverLimitExceeded``0`迭代次数超过 `options.MaxIterations` 或函数计算次数超过 `options.MaxFunctionEvaluations`
`OutputFcnStop``–1`由输出函数或绘图函数停止。
`NoFeasiblePointFound``–2`求解器找不到满足所有约束的点。
`TimeLimitExceeded``–5`优化时间超过 `options.MaxTime`

`paretosearch` 的退出标志等效数值含义
`SolverConvergedSuccessfully``1``options.MaxStallGenerations` 代内间距值相对变化的几何平均值小于 `options.FunctionTolerance`，且最终间距小于过去 `options.MaxStallGenerations` 代内的均值间距。
`SolverLimitExceeded``0`代数超出 `options.MaxGenerations`
`OutputFcnStop``–1`由输出函数或绘图函数停止。
`NoFeasiblePointFound``–2`求解器找不到满足所有约束的点。
`TimeLimitExceeded``–5`优化时间超过 `options.MaxTime`

• `'MultiStart'``'GlobalSearch'` 从局部求解器返回输出结构体。此外，输出结构体包含以下字段：

• `globalSolver` - `'MultiStart'``'GlobalSearch'`

• `objectiveDerivative` - 采用本节末尾描述的值。

• `constraintDerivative` - 采用本节末尾描述的值，或当 `prob` 没有非线性约束时采用 `"auto"`

• `solver` - 局部求解器，例如 `'fmincon'`

• `local` - 包含有关优化的额外信息的结构体。

• `sol` - 局部解，以 `OptimizationValues` 对象的向量形式返回。

• `x0` - 局部求解器的初始点，以元胞数组形式返回。

• `exitflag` - 局部解的退出标志，以整数向量形式返回。

• `output` - 结构体数组，每个局部解对应一行。每行是一个局部输出结构体，对应一个局部解。

`solve``output` 结构体中包含额外字段 `Solver`，用于标识所使用的求解器，例如 `'intlinprog'`

`Solver` 是非线性 Optimization Toolbox™ 求解器时，`solve` 包含一个或两个描述导数估计类型的额外字段。`objectivederivative` 和（如果合适的话）`constraintderivative` 字段可以采用以下值：

• `"reverse-AD"`，表示反向自动微分

• `"forward-AD"`，表示正向自动微分

• `"finite-differences"`，表示有限差分估计

• `"closed-form"`，表示线性或二次函数

• `Variables` - 对应于每个问题变量的字段。每个问题变量名称都是一个包含两个字段的结构体：

• `Lower` - 与变量的 `LowerBound` 属性关联的拉格朗日乘数，以与变量大小相同的数组形式返回。非零条目意味着解在下界处。这些乘数以如下结构表示：`lambda.Variables.variablename.Lower`

• `Upper` - 与变量的 `UpperBound` 属性关联的拉格朗日乘数，以与变量大小相同的数组形式返回。非零条目意味着解在上界处。这些乘数以如下结构表示：`lambda.Variables.variablename.Upper`

• `Constraints` - 对应于每个问题约束的字段。每个问题约束的结构如下：字段名称为约束名称，值是与约束大小相同的数值数组。非零条目意味着约束在解处为活动状态。这些乘数以如下结构表示：`lambda.Constraints.constraintname`

注意

约束数组的元素都具有相同的比较（`<=``==``>=`），并且均为相同的类型（线性、二次或非线性）。

## 算法

### 自动微分

• 对于一般的非线性目标函数，`fmincon` 默认选择反向 AD。对于非线性约束函数，如果其非线性约束的数量小于变量数目，`fmincon` 默认选择反向 AD。否则，`fmincon` 默认选择正向 AD。

• 对于一般的非线性目标函数，`fminunc` 默认选择反向 AD。

• 对于最小二乘目标函数，`fmincon``fminunc` 对目标函数默认选择正向 AD。有关基于问题的最小二乘目标函数的定义，请参阅Write Objective Function for Problem-Based Least Squares

• 当目标向量中的元素数大于或等于变量数时，`lsqnonlin` 默认选择正向 AD。否则，`lsqnonlin` 默认选择反向 AD。

• 当方程数大于或等于变量数时，`fsolve` 默认选择正向 AD。否则，`fsolve` 默认选择反向 AD。

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