% taylor_exp.m
%  Plot the N-term Taylor series for y=exp(x).
%
%  exp(x) = 1 + x/1! + x^2/2! + x^3/3! + ...
%
n = input ( 'Enter the maximum Taylor polynomial degree. ' );
a = input ( 'Enter the lower X limit (such as 0): ' );
b = input ( 'Enter the upper X limit (such as 1): ' );
%
%  Create a list of 101 equally spaced x values between a and b.
%
dots = 101;
x = linspace ( a, b, dots );
f = exp ( x );
p = zeros ( 1, dots );
%
%  There is a "stepping stone" rule for the next term to add.
%    Term(i) = Term(i-1) * x / i
%
hold on
%
%  Plot the exponential curve.
%
plot ( x, f, 'b-', 'linewidth', 3 );
grid on
xlabel ( '<-- X -->' );
ylabel ( '<-- Y -->' );

for i = 0 : n
%
%  Remove previous graph.
%
  if ( 0 < i )
    plot ( x, p, 'w-', 'linewidth', 3 );
  end

  if ( i == 0 )
    term = ones ( 1, dots );
  else
    term = term .* x / i;  % <-- x^i/i! = x^(i-1)/(i-1)! * ( x / i )
  end
%
%  Adding TERM moves the Taylor polynomial from degree I-1 to degree I.
%
  p = p + term;
%
%  Plot the new Taylor polynomial.
%
  plot ( x, p, 'r-', 'linewidth', 3 );
  s = sprintf ( 'Polynomial of degree %d', i );
  title ( s );
  if ( i < n )  
    disp ( 'Press RETURN for next plot:' );
    pause;
  else
    disp ( 'That''s all!' );
  end

end

hold off
%
%  Save a JPG copy of the last plot.
%
print ( '-djpeg', 'taylor_exp.jpg' );
