% Secant method to solve 
%   f(x)=x -cos(x) = 0
%   
%   Remark: f'(x) is not needed.

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



x(1) = 0.5;
x(2) = 0.78;  

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

for k=2:4
  ylabel('Y-axis');
  xlabel('X-axis');
   y(k-1) = x(k-1)-cos(x(k-1)); 
   y(k) = x(k)-cos(x(k));
   % formula of secant method
   x(k+1) = x(k) -  (y(k))/( (y(k) - y(k-1))/(x(k)-x(k-1)) )
   
   %Below is just for plotting 
   x2 = 0:0.1:1;
   ytmp= x2 - cos(x2);
   line_tmp = y(k-1) + (y(k)-y(k-1))/(x(k)-x(k-1))*(x2-x(k-1));
   
   plot(x2,ytmp, x2, line_tmp, 'r')
   hold on
   plot(x(k),y(k),'ko','linewidth',5);
   plot(x(k-1),y(k-1),'ko','linewidth',5);
   text(x(k+1),0,['\uparrow p',num2str(k)]);
   
   grid on
   hold on  
   pause
 end
