newton raphson method in matlab

The Newton-Raphson method is an iterative algorithm used to find the roots of a function. This algorithm requires an initial guess, and then successively refines this guess until a root is found. Here is an implementation of the Newton-Raphson method in MATLAB:

main.m
function [x, fx, iter] = newton_raphson(f, df, x0, tol, max_iter)
% This function finds the root of a function using the Newton-Raphson method
% Inputs:
%   f: the function to find the root of
%   df: the derivative of the function
%   x0: the initial guess
%   tol: the tolerance of the algorithm
%   max_iter: the maximum number of iterations
% Outputs:
%   x: the estimated root
%   fx: the function value at the root
%   iter: the number of iterations taken

iter = 0;
while iter < max_iter
    fx = f(x0);
    if abs(fx) < tol
        break;
    end

    dfx = df(x0);
    if dfx == 0
        error("Newton-Raphson method failed. Derivative is zero.");
    end

    x = x0 - fx / dfx;
    if abs(x - x0) < tol
        break;
    end

    x0 = x;
    iter = iter + 1;
end

if iter == max_iter
    warning("Newton-Raphson method reached maximum iterations.");
end
end
871 chars
39 lines

Here is an example usage of the function for finding the positive root of the function f(x) = x^2 - 2:

main.m
f = @(x) x^2 - 2;
df = @(x) 2*x;
x0 = 1.5;
tol = 1e-6;
max_iter = 100;

[x, fx, iter] = newton_raphson(f, df, x0, tol, max_iter);
fprintf("The root is %f, found after %d iterations with function value %f.", x, iter, fx);
221 chars
9 lines

This code will output the value of the root found, the number of iterations taken, and the final function value at the root.

gistlibby LogSnag