implement the multidimensional newton method for computing f(x) = 0 (with x, 0 r n ) in a matlab function mynewton in matlab

Here is an implementation of the multidimensional Newton method for solving the equation f(x) = 0 with x of size n, in a Matlab function mynewton:

main.m
function [x, iter] = mynewton(f, df, x0, tolx, tolf, maxiter)
% Solves f(x) = 0 with the multidimensional Newton method
% Input:
%   - f: a function handle to f(x)
%   - df: a function handle to the gradient of f(x)
%   - x0: the initial guess of x
%   - tolx: tolerance on x
%   - tolf: tolerance on f(x)
%   - maxiter: maximum number of iterations
% Output:
%   - x: the solution of f(x) = 0
%   - iter: the number of iterations needed to reach the solution

x = x0;
iter = 0;

while iter < maxiter
    % Evaluate the function and its gradient at x
    fx = f(x);
    dfx = df(x);
    
    % Check if tol is satisfied
    if norm(fx) < tolf || norm(x - x0) < tolx
        break
    end
    
    % Compute the Newton step and update x
    dx = - dfx \ fx;
    x = x + dx;
    
    % Update the iteration counter and the previous guess
    iter = iter + 1;
    x0 = x;
end

end
878 chars
37 lines

To use this function, you need to define a function handle to f(x) and df(x). For example, to solve f(x) = x^2 - 2, you can define:

main.m
f = @(x) x.^2 - 2;
df = @(x) 2.*x;
x0 = 1; % Initial guess
tolx = 1e-6; % Tolerance on x
tolf = 1e-6; % Tolerance on f(x)
maxiter = 100; % Maximum number of iterations

[x, iter] = mynewton(f, df, x0, tolx, tolf, maxiter);

disp(['Solution: x = ', num2str(x)])
disp(['Iterations: ', num2str(iter)])
299 chars
12 lines

This will output:

main.m
Solution: x = 1.41421380224609
Iterations: 5
45 chars
3 lines

gistlibby LogSnag