function Newton_algorithm_plot
clc
clear all
close all

%% Parameters
f=@(x) x^3+2*x^2-3*x-1;  % function
dd=1;    % if haveyou have the dd =1; If DONT have dd=0
d=@(x) 3*x^2+4*x-3;   % first derivative
a=1;   %Intial Guess 
ee=1e-10;   % error tolerance
Nmax=50; %maximum iteratoins 
xmin=0;  %bounds for ploting
xmax=2; %bounds for ploting

%% Calculating The Derivative
if dd<0.5
syms x
t=diff(f,x);
d=matlabFunction(t);
end

%% 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)
hold on
plot(a,feval(f,a),'*r','LineWidth',5)
plot([xmin,xmax],[0,0],'--','Color',[.5,0.5,0.5])
md=feval(d,a); 
b=feval(f,a)-md*a;
yd=md*xmin+b; ydd=md*xmax+b;
plot([xmin,xmax],[yd,ydd],'k-.')
da=0.1*(abs(ymin)+abs(ymax));
axis([xmin,xmax,ymin-da,ymax+da]);
title('\fontsize{17}Newton Algorithm {\fontsize{9}Dylan Walsh}')
xlabel('X','FontSize',14)
ylabel('Y','FontSize',14)
annotation(h,'textbox',...
    [0.206 0.5 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; %Iteration counter
fprintf('Starting Calculatins \n ----------------------\n k\t   x_n\n')
p=a; m=feval(f,p); md=feval(d,p);
pp=2.32; X=10;
while X>ee
     fprintf('\n%3.f \t %1.10f',k,p)
    p=p-m/md;
     m=feval(f,p); md=feval(d,p);
          addplot(p,k,m,md,h,xmin,xmax) %plotting each iteration
    X=abs(p-pp);  % error calculation for stopping
    pp=p;   %pp=p(n)
       if k>Nmax
             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 each iteration to the plot
function addplot(p,k,m,md,h,xmin,xmax)
plot(p,m,'ob')
b=m-md*p;
yd=md*xmin+b; ydd=md*xmax+b;
plot([xmin,xmax],[yd,ydd],'k-.')
annotation(h,'rectangle',...
    [0.206 0.35 0.3 0.4],...
    'LineStyle','none',...
    'FaceColor',[1 1 1]);
annotation(h,'textbox',...
     [0.206 0.5 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