function secant_algorithm_plot
clc
clear all
close all

%% Parameters
f=@(x) x^3+2*x^2-3*x-1;  % function
a=2;   %Intial Guess 
b=1;   % Primer
ee=1e-10;   % error tolerance
Nmax=50; %maximum iteratoins 
xmin=b; xmax=a; % may need to switch a and b around to make xmin be th smallest number and xmax the biggest number
                            % you can also change b and a to zoom into an area of interest
                            
%% Start Ploting 
  n=1000;
 xx=linspace(xmin,xmax,n);
 yy=zeros(1,n);
 for t=1:n
     yy(1,t)=feval(f,xx(1,t));
 end
 ymin=min(yy);
 ymax=max(yy);
h=figure;
plot(xx,yy,'k','LineWidth',2)
hold on
plot([a,b],[feval(f,a),feval(f,b)],'-r')
plot([xmin,xmax],[0,0],'--','Color',[.5,0.5,0.5])
da=0.1*(abs(ymin)+abs(ymax));
axis([xmin,xmax,ymin-da,ymax+da]);
title('\fontsize{17}Secant Algorithm {\fontsize{9}Dylan Walsh}')
xlabel('X','FontSize',14)
ylabel('Y','FontSize',14)
annotation(h,'textbox',...
    [0.206 0.7 0.182 0.133],...
    'String',{'Starting Point'},...
    'FontWeight','bold',...
    'FontSize',16,...
    'FontName','Times New Roman',...
    'FitBoxToText','off',...
    'EdgeColor',[1 1 1]);
pause(2)

%% Algorithm
k=0; % Starting iteration counter
fprintf('Starting Calculatins \n ----------------------\n k\t   x_n\n')
fprintf('\n%3.f \t %1.10f',k,a)
k=1;
pp=b; m=feval(f,pp);
ppp=a;  m2=feval(f,ppp);
X=10;
while X>ee
     fprintf('\n%3.f \t %1.10f',k,pp)
    p=pp-m*(pp-ppp)/(m-m2);
    
    m2=m; m=feval(f,p); 
    addplot(p,pp,k,m,m2,h,xmin,xmax)
    X=abs(p-pp);  % error calculation for stopping
    ppp=pp; %ppp=p(n-1)
    pp=p;%pp=p(n)
       if k>Nmax %stopping criteria for max iterations
             fprintf('\n\n\n!!!!Max Iterations Reached!!!!!!!\n') 
               break
        end
   k=k+1;
end
 if k<Nmax
             fprintf('\n\nRoot=%20.10f\n',p)
 end
end
%% Adding points to the plot
function addplot(p,pp,k,m,m2,h,xmin,xmax)
plot(p,0,'ob')
plot([p,p],[0,m],'--','Color',[.5,0.5,0.5])
plot(p,m,'ob')
pause(0.5)
d=(m-m2)/(p-pp)*(xmin-p)+m;
dd=(m-m2)/(p-pp)*(xmax-p)+m;
plot([xmin,xmax],[d,dd],'-b')
annotation(h,'rectangle',...
    [0.206 0.55 0.3 0.3],...
    'LineStyle','none',...
    'FaceColor',[1 1 1]);
annotation(h,'textbox',...
     [0.206 0.7 0.3 0.133],...
    'String',{'Iteration=' k 'x_n=' p},...
    'FontWeight','bold',...
    'FontSize',16,...
    'FontName','Times New Roman',...
    'FitBoxToText','off',...
    'EdgeColor',[1 1 1]);
pause(0.5)
end