%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Newton's Method for Minimizer of a Unimodal Function %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 A=[];
%%
%%   Select Parameters: endpoints & error tolerance
   x_current = 3 ,  eps= 1e-10 
%
%%   Initialize variables
%%   
   diff_current = eps +1;              % artificial to start (flag)
%%
%%   Begin interation loop
 while abs(diff_current) > eps,
     deriv  = phi_1(x_current);        % Evaluate derivative  
     deriv2 = phi_2(x_current);        % Evaluate 2-nd derivative 
     diff_new = -deriv/deriv2;         % compute the update
     x_new = x_current + diff_new;     % update approx. minimizer
	 F= phi(x_new);                % evaluate the function \phi
	 diff_current = diff_new;  
	 x_current = x_new;        
     A=[ A                             % build matrix of info
         [ x_current F  diff_current deriv] ];  
     
	 end                           % end of do-while
	 
	 
 A                                     % Output iterates and info

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%     function evaluator (needs to be placed in phi.m)   %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
     
function [phi]=phi(x) 
    phi = x^2 + 4 * cos(x);
	  end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%  derivative evaluator (needs to be placed in phi_1.m)  %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [phi_1] = phi_1(x) 
    phi_1 = 2*x - 4 * sin(x);
	  end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%     2-nd derivative evaluator (write to phi_2.m)       %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [phi_2] = phi_2(x) 
    phi_2 = 2 - 4 * cos(x);
	  end
