function[x_k,iter_hist] = newton(x_0,step_tol,fn_tol,maxiter,cost_fn) % This matlab function uses Newton's method to compute % a solution of the equation f(x)=0. % Initialize and check to see if x_0 is a solution. x_k = x_0; [f,J] = feval(cost_fn,x_k); fprintf('iter=%d |f(x_0)|=%2.3e |e|=%2.3e\n',0,norm(f),0) if f == 0 disp(' f(x_0) = 0. ') return end % Save iteration history. % iter_hist = [iteration, |f|, |step|]; iter_hist = [0, norm(f), 0]; % Newton's Method for k = 1:maxiter e = J\f; x_k = x_k - e; [f,J] = feval(cost_fn,x_k); % Save iteration info and output to screen. nf = norm(f); ne = norm(e); iter_hist = [iter_hist; [k, nf, ne]]; fprintf('iter=%d |f(x_k)|=%2.3e |e|=%2.3e\n',k,nf,ne) % Check the stopping criteria if norm(f) < fn_tol disp(' |f(x_k)| stopping tolerance met.') return elseif norm(e) < step_tol disp(' error stopping tolerance met.') return elseif k == maxiter disp(' Max number of iterations reached.') return end end