newton method with jacobian in matlab

To use the Newton method with Jacobian in MATLAB, you can follow these steps:

  1. Define the function that you want to optimize using the Newton method. Let's call this function fun.
main.m
function F = fun(x)
    F = [2*x(1)^2 + x(2)^2 - 4; 
         x(1)^2 - x(2) - 1];
end
86 chars
5 lines
  1. Define the Jacobian matrix of the function fun.
main.m
function J = jacobian(x)
    J = [4*x(1) 2*x(2); 
         2*x(1) -1];
end
75 chars
5 lines
  1. Choose an initial guess for the solution x0.
main.m
x0 = [1; 1];
13 chars
2 lines
  1. Set the maximum number of iterations for the Newton method algorithm.
main.m
max_iter = 20;
15 chars
2 lines
  1. Set the tolerance for convergence of the algorithm.
main.m
tol = 1e-6;
12 chars
2 lines
  1. Implement the Newton method algorithm with the Jacobian matrix in a loop.
main.m
iter = 1;
x = x0;
while iter <= max_iter
    F = fun(x);
    J = jacobian(x);
    delta_x = -J\F;
    x = x + delta_x;
    if norm(delta_x) < tol
        break
    end
    iter = iter + 1;
end
193 chars
13 lines
  1. Display the solution x.
main.m
disp(x);
9 chars
2 lines

That's it! You can use this code template to apply the Newton method with Jacobian in MATLAB for your own functions.

gistlibby LogSnag