# 使用梯度和黑塞矩阵的最小化

`$f\left(x\right)=\sum _{i=1}^{n-1}\left({\left({x}_{i}^{2}\right)}^{\left({x}_{i+1}^{2}+1\right)}+{\left({x}_{i+1}^{2}\right)}^{\left({x}_{i}^{2}+1\right)}\right),$`

```options = optimoptions(@fminunc,'Algorithm','trust-region',... 'SpecifyObjectiveGradient',true,'HessianFcn','objective');```

```n = 1000; xstart = -ones(n,1); xstart(2:2:n) = 1;```

$f$ 的最小值。

`[x,fval,exitflag,output] = fminunc(@brownfgh,xstart,options);`
```Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance. ```

`disp(fval)`
``` 2.8709e-17 ```
`disp(exitflag)`
``` 1 ```
`disp(output)`
``` iterations: 7 funcCount: 8 stepsize: 0.0039 cgiterations: 7 firstorderopt: 4.7948e-10 algorithm: 'trust-region' message: 'Local minimum found....' constrviolation: [] ```

`disp(max(x))`
``` 1.1987e-10 ```
`disp(min(x))`
``` -1.1987e-10 ```

### 辅助函数

```function [f,g,H] = brownfgh(x) %BROWNFGH Nonlinear minimization problem (function, its gradients % and Hessian) % Documentation example % Copyright 1990-2008 The MathWorks, Inc. % Evaluate the function. n=length(x); y=zeros(n,1); i=1:(n-1); y(i)=(x(i).^2).^(x(i+1).^2+1)+(x(i+1).^2).^(x(i).^2+1); f=sum(y); % % Evaluate the gradient. if nargout > 1 i=1:(n-1); g = zeros(n,1); g(i)= 2*(x(i+1).^2+1).*x(i).*((x(i).^2).^(x(i+1).^2))+... 2*x(i).*((x(i+1).^2).^(x(i).^2+1)).*log(x(i+1).^2); g(i+1)=g(i+1)+... 2*x(i+1).*((x(i).^2).^(x(i+1).^2+1)).*log(x(i).^2)+... 2*(x(i).^2+1).*x(i+1).*((x(i+1).^2).^(x(i).^2)); end % % Evaluate the (sparse, symmetric) Hessian matrix if nargout > 2 v=zeros(n,1); i=1:(n-1); v(i)=2*(x(i+1).^2+1).*((x(i).^2).^(x(i+1).^2))+... 4*(x(i+1).^2+1).*(x(i+1).^2).*(x(i).^2).*((x(i).^2).^((x(i+1).^2)-1))+... 2*((x(i+1).^2).^(x(i).^2+1)).*(log(x(i+1).^2)); v(i)=v(i)+4*(x(i).^2).*((x(i+1).^2).^(x(i).^2+1)).*((log(x(i+1).^2)).^2); v(i+1)=v(i+1)+... 2*(x(i).^2).^(x(i+1).^2+1).*(log(x(i).^2))+... 4*(x(i+1).^2).*((x(i).^2).^(x(i+1).^2+1)).*((log(x(i).^2)).^2)+... 2*(x(i).^2+1).*((x(i+1).^2).^(x(i).^2)); v(i+1)=v(i+1)+4*(x(i).^2+1).*(x(i+1).^2).*(x(i).^2).*((x(i+1).^2).^(x(i).^2-1)); v0=v; v=zeros(n-1,1); v(i)=4*x(i+1).*x(i).*((x(i).^2).^(x(i+1).^2))+... 4*x(i+1).*(x(i+1).^2+1).*x(i).*((x(i).^2).^(x(i+1).^2)).*log(x(i).^2); v(i)=v(i)+ 4*x(i+1).*x(i).*((x(i+1).^2).^(x(i).^2)).*log(x(i+1).^2); v(i)=v(i)+4*x(i).*((x(i+1).^2).^(x(i).^2)).*x(i+1); v1=v; i=[(1:n)';(1:(n-1))']; j=[(1:n)';(2:n)']; s=[v0;2*v1]; H=sparse(i,j,s,n,n); H=(H+H')/2; end end```