% Newton's method to solve 
%   f(x)=x^2 + 2x-3.0 = 0
%   
%   Remark: f'(x) = 2x+2

clear all;
disp('Newton method: ');


x1=2.5; %%% try 0.7 as well
x(1) = x1   
y(1) = x(1)^2 + 2.0*x(1)-3.0
yp(1) = 2.0*x(1) + 2.0

text(x(1),0,['\uparrow p',num2str(0)]);
hold on

for k=1:4
  ylabel('Y-axis');
  xlabel('X-axis');
  
   x(k+1) = x(k) - y(k)/yp(k)
   y(k+1) = x(k+1)*x(k+1) + 2.0*x(k+1)-3.0
   yp(k+1) = 2.0*x(k+1) + 2.0
   
   x2 = -1:0.1:pi;
   
   ytmp= x2.^2 +2.0.*x2 - 3.0;
   line_tmp = y(k) + yp(k)*(x2-x(k));
   
   plot(x2,ytmp, x2, line_tmp, 'r')
   hold on
   plot(x(k),y(k),'ko','linewidth',5);
   text(x(k+1),0,['\uparrow p',num2str(k)]);
   
   grid on
   hold on  
   pause
 end
