% Programming and Numerical Methods
% MSc in Computational and Applied Physics

% Code 19: Newton's method for solving [f(x,y) g(x,y)] = [0 0]
% A. Meseguer (2007)

% Requires Ffun and Jfun (vector field and its Jacobian)


function [x,xvec,F,iter] = newtonsys(Ffun,Jfun,x0,tol,nmax)

iter = 0; err = tol + 1; x = x0; xvec = [x0];
while err > tol & iter <= nmax
    J = feval(Jfun,x);
    F = feval(Ffun,x);
    delta = - J\F;
    x = x + delta;
    err = norm(delta);
    iter = iter + 1;
    xvec = [xvec , x];
end
F = norm(feval(Ffun,x));

%[x,F,iter] = newtonsys(@Ffun,@Jfun,[0 ; 0],1e-5,20)
