# 求解不含和含雅可比矩阵的非线性方程组

`$\begin{array}{l}F\left(1\right)=1-{x}_{1}\\ F\left(2\right)=10\left({x}_{2}-{x}_{1}^{2}\right)\\ F\left(3\right)=1-{x}_{3}\\ F\left(4\right)=10\left({x}_{4}-{x}_{3}^{2}\right)\\ ⋮\\ F\left(n-1\right)=1-{x}_{n-1}\\ F\left(n\right)=10\left({x}_{n}-{x}_{n-1}^{2}\right).\end{array}$`

`$\begin{array}{l}{J}_{ii}\left(x\right)=-1\\ {J}_{\left(i+1\right)i}=-20{x}_{i}\\ {J}_{\left(i+1\right)\left(i+1\right)}=10.\end{array}$`

```n = 64; x0(1:n,1) = -1.9; x0(2:2:n,1) = 2; [x,F,exitflag,output,JAC] = fsolve(@multirosenbrock,x0);```
```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. ```

`disp(norm(x-ones(size(x))))`
``` 0 ```
`disp(output.funcCount)`
``` 1043 ```

`fsolve` 找到了解，并为此执行了 1000 多次函数计算。

```opts = optimoptions('fsolve','SpecifyObjectiveGradient',true); [x2,F2,exitflag2,output2,JAC2] = fsolve(@multirosenbrock,x0,opts);```
```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. ```

`disp(norm(x2-ones(size(x2))))`
``` 0 ```
`disp(output2.funcCount)`
``` 21 ```

`fsolve` 返回与上一个解相同的解，但为此执行的函数计算是 20 次左右，而不是 1000 多次。一般情况下，使用雅可比矩阵可以减少函数计算次数并提高稳健性，尽管此示例并未说明稳健性得到了改进。

### 辅助函数

```function [F,J] = multirosenbrock(x) % Get the problem size n = length(x); if n == 0, error('Input vector, x, is empty.'); end if mod(n,2) ~= 0 error('Input vector, x ,must have an even number of components.'); end % Evaluate the vector function odds = 1:2:n; evens = 2:2:n; F = zeros(n,1); F(odds,1) = 1-x(odds); F(evens,1) = 10.*(x(evens)-x(odds).^2); % Evaluate the Jacobian matrix if nargout > 1 if nargout > 1 c = -ones(n/2,1); C = sparse(odds,odds,c,n,n); d = 10*ones(n/2,1); D = sparse(evens,evens,d,n,n); e = -20.*x(odds); E = sparse(evens,odds,e,n,n); J = C + D + E; end end```