% function [x] = fpoint(g, x0, tolerance, maxiter, printflag) % fpoint fixed point iteration % g = function to iterate % x0 = initial guess % tolerance = maximum error desired % maxiter = maximum iterations % printflag = true, display intermediate results % printflag = false, display only the final result x = x0; if printflag fprintf('%3s%19s%19s\n', 'n','x','err'); end n = 1; while n <= maxiter gx = g(x); err = abs(x - gx); x = gx; if err < tolerance break; % exit loop end if printflag fprintf('%3d%19.10e%19.10e\n', n,x,err); end n = n + 1; end if (n > maxiter) fprintf('Failure to converge in %d iterations\n', maxiter); end % x is automatically returned here end