% Define the function
func = @(x) x^2 - 4;
% Initial guess
initial_guess = 3;
% Tolerance
tolerance = 1e-6;
% Maximum iterations
max_iter = 100;
% Call the newton_raphson function
[root, iter] = newton_raphson(func, initial_guess, tolerance, max_iter);
% Display the result
if ~isnan(root)
fprintf('Root found at %f after %d iterations.\n', root, iter);
else
fprintf('Root not found within maximum iterations.\n');
end
Sure, let's consider another example. Suppose we want to find a root of the function ( f(x) =
e^{-x} - x ) using the Newton-Raphson method. Here's how you can implement it in MATLAB:
% Define the function
func = @(x) exp(-x) - x;
% Initial guess
initial_guess = 0.5;
% Tolerance
tolerance = 1e-6;
% Maximum iterations
max_iter = 100;
% Call the newton_raphson function
[root, iter] = newton_raphson(func, initial_guess, tolerance, max_iter);
% Display the result
if ~isnan(root)
fprintf('Root found at %f after %d iterations.\n', root, iter);
else
fprintf('Root not found within maximum iterations.\n');
end
```
This code will find the root of the function ( f(x) = e^{-x} - x ) starting from the initial guess
of ( x = 0.5 ). Adjust the parameters as needed for your specific problem.