newton-raphson iteration in matlab

The Newton-Raphson method is an iterative technique to find the root of a function. The formula for the algorithm is:

main.m
x(i+1) = x(i) - f(x(i))/f'(x(i))
33 chars
2 lines

Where x(i) is the current guess for the root, f(x(i)) is the value of the function at that guess and f'(x(i)) is the first derivative of the function at that guess. This process is repeated until a sufficiently accurate estimate of the root is obtained.

Here is an example implementation of the Newton-Raphson method in MATLAB:

main.m
% Define the function that we want to find the root of
f = @(x) x^3 - 5*x^2 + 6*x - 2;

% Define the first derivative of the function
df = @(x) 3*x^2 - 10*x + 6;

% Set an initial guess for the root
x0 = 1;

% Set a tolerance level for convergence
tol = 10^-6;

% Initialize the error to a high value
err = Inf;

% Loop until the error is below the tolerance level
while err > tol
    % Calculate the next estimate of the root
    x1 = x0 - f(x0)/df(x0);
    
    % Calculate the error between the current and previous estimates
    err = abs(x1 - x0);
    
    % Set the current estimate to be the previous estimate for the next iteration
    x0 = x1;
end

% Output the final estimate of the root
disp(['The root of the function is approximately ', num2str(x1)])
764 chars
30 lines

In this example, we define the function f and its first derivative df, set an initial guess for the root x0, and a tolerance level for convergence tol. We then loop through the Newton-Raphson formula until the error between the current and previous estimates of the root is less than the tolerance level. Lastly, we output the final estimate of the root.

gistlibby LogSnag