# 使用模拟退火算法进行最小化

### 简单目标函数

``` min f(x) = (4 - 2.1*x1^2 + x1^4/3)*x1^2 + x1*x2 + (-4 + 4*x2^2)*x2^2; x ```

`type simple_objective`
```function y = simple_objective(x) %SIMPLE_OBJECTIVE Objective function for PATTERNSEARCH solver % Copyright 2004 The MathWorks, Inc. x1 = x(1); x2 = x(2); y = (4-2.1.*x1.^2+x1.^4./3).*x1.^2+x1.*x2+(-4+4.*x2.^2).*x2.^2; ```

### 尽量减少使用 `simulannealbnd`

```ObjectiveFunction = @simple_objective; x0 = [0.5 0.5]; % Starting point rng default % For reproducibility [x,fval,exitFlag,output] = simulannealbnd(ObjectiveFunction,x0)```
```simulannealbnd stopped because the change in best function value is less than options.FunctionTolerance. ```
```x = 1×2 -0.0896 0.7130 ```
```fval = -1.0316 ```
```exitFlag = 1 ```
```output = struct with fields: iterations: 2948 funccount: 2971 message: 'simulannealbnd stopped because the change in best function value is less than options.FunctionTolerance.' rngstate: [1x1 struct] problemtype: 'unconstrained' temperature: [2x1 double] totaltime: 1.4887 ```

`simulannealbnd` 返回四个输出参量：

• `x` - 找到最佳点

• `fval` - 最佳点处的函数值

• `exitFlag` - 对应于函数停止原因的整数

• `output` - 有关优化步骤的信息

### 有界约束最小化

```lb = [-64 -64]; ub = [64 64];```

`[x,fval,exitFlag,output] = simulannealbnd(ObjectiveFunction,x0,lb,ub);`
```simulannealbnd stopped because the change in best function value is less than options.FunctionTolerance. ```
`fprintf('The number of iterations was : %d\n', output.iterations);`
```The number of iterations was : 2428 ```
`fprintf('The number of function evaluations was : %d\n', output.funccount);`
```The number of function evaluations was : 2447 ```
`fprintf('The best function value found was : %g\n', fval);`
```The best function value found was : -1.03163 ```

### 尽量减少使用附加参数

``` min f(x) = (a - b*x1^2 + x1^4/3)*x1^2 + x1*x2 + (-c + c*x2^2)*x2^2; x ```

`a``b``c` 是目标函数的参数，在优化期间充当常量（它们不会作为最小化的一部分而变化）。为了实现目标函数计算，MATLAB 文件 `parameterized_objective.m` 包含以下代码：

`type parameterized_objective`
```function y = parameterized_objective(x,p1,p2,p3) %PARAMETERIZED_OBJECTIVE Objective function for PATTERNSEARCH solver % Copyright 2004 The MathWorks, Inc. x1 = x(1); x2 = x(2); y = (p1-p2.*x1.^2+x1.^4./3).*x1.^2+x1.*x2+(-p3+p3.*x2.^2).*x2.^2; ```

`simulannealbnd` 仅使用一个参量 `x` 调用目标函数，但目标函数有四个参量：`x``a``b``c`。为了指示哪个变量是参量，请使用匿名函数来捕获附加参量的值（常量 `a``b``c`）。创建一个函数句柄 `ObjectiveFunction` 到一个匿名函数，该函数接受一个输入 `x`，但使用 `x``a``b``c` 调用 `parameterized_objective`。当您创建函数句柄 `ObjectiveFunction` 时，变量 `a``b``c` 具有存储在匿名函数中的值。

```a = 4; b = 2.1; c = 4; % Define constant values ObjectiveFunction = @(x) parameterized_objective(x,a,b,c); x0 = [0.5 0.5]; [x,fval] = simulannealbnd(ObjectiveFunction,x0)```
```simulannealbnd stopped because the change in best function value is less than options.FunctionTolerance. ```
```x = 1×2 0.0898 -0.7127 ```
```fval = -1.0316 ```

### 参考资料

[1] Dixon, L. C. W., and G .P. Szego (eds.).Towards Global Optimisation 2.North-Holland:Elsevier Science Ltd., Amsterdam, 1978.