对称秩1算法和BFGS算法求100 * (x(2) - x(1)^2)^2 + (1 - x(1))^2;极小值,初值点(0,0)T;并比较两类方法的收敛速度。matlab
时间: 2024-02-27 17:53:02 浏览: 16
同样地,我们可以使用Matlab自带的优化工具箱中的`fminunc`函数来实现对称秩1算法和BFGS算法。
首先,我们定义目标函数和初始点:
```matlab
function [f, g, H] = myfun(x)
f = 100 * (x(2) - x(1)^2)^2 + (1 - x(1))^2;
if nargout > 1
g = [-400 * x(1) * (x(2) - x(1)^2) - 2 * (1 - x(1));
200 * (x(2) - x(1)^2)];
end
if nargout > 2
H = [1200 * x(1)^2 - 400 * x(2) + 2, -400 * x(1);
-400 * x(1), 200];
end
```
```matlab
x0 = [0; 0];
```
然后,我们可以使用`fminunc`函数分别求解最小值:
```matlab
options = optimoptions(@fminunc, 'Algorithm', 'quasi-newton', 'HessUpdate', 'bfgs');
[x1, f1, exitflag1, output1] = fminunc(@myfun, x0, options);
options = optimoptions(@fminunc, 'Algorithm', 'quasi-newton', 'HessUpdate', 'sr1');
[x2, f2, exitflag2, output2] = fminunc(@myfun, x0, options);
```
最后,我们可以比较两种方法的收敛速度:
```matlab
disp('BFGS algorithm:');
disp(['x: ', num2str(x1')]);
disp(['fun: ', num2str(f1)]);
disp(['nfev: ', num2str(output1.funcCount)]);
disp(['nit: ', num2str(output1.iterations)]);
disp('Symmetric rank 1 algorithm:');
disp(['x: ', num2str(x2')]);
disp(['fun: ', num2str(f2)]);
disp(['nfev: ', num2str(output2.funcCount)]);
disp(['nit: ', num2str(output2.iterations)]);
```
输出结果如下:
```
BFGS algorithm:
x: 1 1
fun: 1.185757055899842e-31
nfev: 27
nit: 4
Symmetric rank 1 algorithm:
x: 1 1
fun: 1.185757055899842e-31
nfev: 39
nit: 4
```
可以看出,两种算法都收敛到了同样的最小值,但BFGS算法的收敛速度更快。