clear all; close all

% Use Symbolic Variable
syms x; 

% Creat vidObj to store movie

% Prepare the new file.
vidObj = VideoWriter('diff_eg.avi');
open(vidObj);

% Declare f(x)
f = x^2 + 2*x +1;

%ifferentiate f(x)
df = diff(f);


% Loop Through x0 range and plat tangents
i=0;

for x0=-50:50
i = i+1;

m = subs(df,x0);

y0 = subs(f,x0);

%compute c (y-axis Intercept)
c = y0 - m*x0;

%Declare 
tan_eqn = m*x + c;


%Plot f(x) and tangent at (x0,y0)

t1 = ezplot(tan_eqn,[-50 50]);

set(t1,'Color','red');

hold on;

ezplot(f,[-50 50]);

plot(x0,y0,'o','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','r','MarkerSize',10);

text_eqn = sprintf('x0 = %d, y0 = %d',x0,y0);
text(-10,2500,text_eqn);
text_eqn = sprintf('y = %s',char(tan_eqn));
text(-10,2400,text_eqn);

M(i) = getframe; % Load M with current frame
 writeVideo(vidObj,M(i));
 
 hold off;
end


implay(M); % play movie.

%save movie close the file.
close(vidObj);


shg