# jacobian in newton method in matlab

To use the Newton method to solve a system of nonlinear equations in MATLAB, one needs to compute the Jacobian of the system.

Here is an example implementation of the Newton method in MATLAB, where `F` is the system of nonlinear equations, `J` is the Jacobian of `F`, `x0` is the initial guess, `tol` is the tolerance for the solution, and `max_iter` is the maximum number of iterations:

```main.m```function [x, iter] = newton(F, J, x0, tol, max_iter)
iter = 0;
x = x0;
while norm(F(x)) > tol && iter < max_iter
Jx = J(x);
dx = -Jx\F(x);
x = x + dx;
iter = iter + 1;
end
end
```200 chars11 lines```

To use this function, one needs to provide the function handle `F`, the function handle `J`, the initial guess `x0`, the tolerance `tol`, and the maximum number of iterations `max_iter`.

For example, if we want to solve the system of equations `sin(x) + y^2 = 0`, `x^2 + y = 1`, we can define the function handles as follows:

```main.m```F = @(x) [sin(x(1)) + x(2)^2; x(1)^2 + x(2) - 1];
J = @(x) [cos(x(1)), 2*x(2); 2*x(1), 1];
```91 chars3 lines```

Then we can call the `newton` function as follows:

```main.m```x0 = [0; 1];   % initial guess
tol = 1e-6;    % tolerance
max_iter = 100; % maximum number of iterations
[x, iter] = newton(F, J, x0, tol, max_iter); % solve the system
```169 chars5 lines```

After running this code, the solution `x` and the number of iterations `iter` will be returned.

### related categories

gistlibby LogSnag