% Project 1 - Taylor Series Expansion
clc, close all, clear all

disp('This program plots the nth order truncated Taylor Series of f(x)=cos(x).')
disp('The truncated series fn(x), n=0,1,...,10 are expanded about the point x0.')  
disp('All graphs including f(x) = cos(x) are plotted from 0 to 2*pi radians.')
 
again='Y';
while again=='Y'|again=='y'
  close all
  disp(' ')
  x0=input('Enter the point x0 (between 0 and 2*pi)   '); 
  x=linspace(0,2*pi,500);
  fx=cos(x);
  plot(x,fx,'k','Linewidth',1.5) 
  v=[-0.25 2*pi -2 2];
  axis(v)
  xlabel('x (rad)')
  title('f(x) = cos(x) and nth Order Truncated Series (n = 0,1,2,4,6,8,10)')    
  hold on
  fx0=cos(x0);
  fp1=-sin(x0);
  fp2=-cos(x0);
  fp3=sin(x0);
  fp4=cos(x0); 
  fp5=fp1;
  fp6=fp2;
  fp7=fp3;
  fp8=fp4;
  fp9=fp5;
  fp10=fp6;
  f0=fx0*ones(size(x));
  f1=f0+fp1*(x-x0);
  f2=f1+(fp2/2)*(x-x0).^2;
  f3=f2+(fp3/6)*(x-x0).^3;
  f4=f3+(fp4/24)*(x-x0).^4;
  f5=f4+(fp5/120)*(x-x0).^5;
  f6=f5+(fp6/720)*(x-x0).^6;
  f7=f6+(fp7/5040)*(x-x0).^7;
  f8=f7+(fp8/40320)*(x-x0).^8;
  f9=f8+(fp9/362880)*(x-x0).^9;
  f10=f9+(fp10/3628800)*(x-x0).^10;
  pause
  plot(x,f0,'b')
  pause
  plot(x,f1,'r')
  pause
  plot(x,f2,'m')
  pause
  plot(x,f4,'b:')
  pause
  plot(x,f6,'r:')
  pause
  plot(x,f8,'m:')
  pause
  plot(x,f10,'g')
  plot([x0 x0],[-2 fx0],'k:')
  legend('f(x)','f_{0}(x)','f_{1}(x)','f_{2}(x)','f_{4}(x)','f_{6}(x)','f_{8}(x)','f_{10}(x)',0)
  plot([0 0],[-2 2],'k') 
  plot([-0.25 2*pi],[0 0],'k')
  text(x0+0.1  ,-1.8,'x0')
  pause
  close all
  disp(' ')
  again=input('Repeat plot for different xo?  Y or  N    ','s');  
end % while






