## 传递额外参数

### 额外参数、固定变量或数据

 $f\left(x\right)=\left(a-b{x}_{1}^{2}+{x}_{1}^{4}/3\right){x}_{1}^{2}+{x}_{1}{x}_{2}+\left(-c+c{x}_{2}^{2}\right){x}_{2}^{2}$ (1)

### 匿名函数

1. 编写包含以下代码的文件：

```function y = parameterfun(x,a,b,c) y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)*x(2) + ... (-c + c*x(2)^2)*x(2)^2;```

2. 通过在 MATLAB® 提示符下输入以下命令，为参数赋值并定义匿名函数的函数句柄 `f`

```a = 4; b = 2.1; c = 4; % Assign parameter values x0 = [0.5,0.5]; f = @(x)parameterfun(x,a,b,c);```

3. 使用匿名函数调用求解器 `fminunc`

`[x,fval] = fminunc(f,x0)`
在命令行窗口中显示以下输出：
```Local minimum found. Optimization completed because the size of the gradient is less than the default value of the function tolerance. x = -0.0898 0.7127 fval = -1.0316```

```a = 4; b = 2.1; c = 4; f = @(x)parameterfun(x,a,b,c)```

`[x,fval] = fminunc(f,x0)`

```a = 3; f = @(x)parameterfun(x,a,b,c)```

```fh = @(x,xdata)(sin(x).*xdata +(x.^2).*cos(xdata)); x = pi; xdata = pi*[4;2;3]; fh(x, xdata)```
```ans = 9.8696 9.8696 -9.8696```

```% Assume ydata exists x = lsqcurvefit(fh,x,xdata,ydata)```

### 嵌套函数

• 接受 `a``b``c``x0` 作为输入

• 包含目标函数作为嵌套函数

• 调用 `fminunc`

```function [x,fval] = runnested(a,b,c,x0) [x,fval] = fminunc(@nestedfun,x0); % Nested function that computes the objective function function y = nestedfun(x) y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)*x(2) +... (-c + c*x(2)^2)*x(2)^2; end end```

```a = 4; b = 2.1; c = 4;% Assign parameter values x0 = [0.5,0.5]; [x,fval] = runnested(a,b,c,x0)```

### 全局变量

1. 编写函数文件：

```function y = globalfun(x) global a b c y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)*x(2) + ... (-c + c*x(2)^2)*x(2)^2;```

2. 在您的 MATLAB 工作区中，定义变量并运行 `fminunc`

```global a b c; a = 4; b = 2.1; c = 4; % Assign parameter values x0 = [0.5,0.5]; [x,fval] = fminunc(@globalfun,x0)```