how to implement newtons method in matlab

Newton's method is an iterative numerical method for finding the roots of a function. In matlab, we can implement Newton's method as follows:

main.m
function [x, iterations] = newton(f, df, x0, tol, maxit)
% Inputs:
%   f: function handle for the function to find roots of
%   df: function handle for the first derivative of f
%   x0: initial guess
%   tol: tolerance for stopping criterion
%   maxit: maximum number of iterations
% Outputs:
%   x: approximation of the root
%   iterations: number of iterations required

% initialize variables
x = x0;
fx = f(x);
iterations = 0;

% loop until stopping criterion is satisfied or maximum iterations reached
while(abs(fx) > tol && iterations < maxit)
    x = x - fx/df(x);
    fx = f(x);
    iterations = iterations + 1;
end
end
628 chars
24 lines

The inputs to the newton function are:

  • f: matlab function handle for the function to find roots of
  • df: matlab function handle for the first derivative of f
  • x0: initial guess for root
  • tol: tolerance for stopping criterion (e.g. 1e-6)
  • maxit: maximum number of iterations to run (e.g. 100)

The function outputs the approximation of the root and the number of iterations required.

To use the newton function, you can define an anonymous function for f and df (or use pre-defined functions), call the newton function with your inputs, and print the results:

main.m
% define function and derivative
f = @(x) x.^3 - 2*x - 5;
df = @(x) 3*x.^2 - 2;

% call newton function
[x, iterations] = newton(f, df, 2, 1e-6, 100);

% print results
fprintf('Approximate Root: %.6f\n', x);
fprintf('Iterations Required: %d\n', iterations);
258 chars
11 lines

gistlibby LogSnag