close all; clear all; clc; h = figure; axis tight manual % this ensures that getframe() returns a consistent size filename = 'DiffQuot.gif'; x=[-1:0.01:3]; y = inline('-(2/5 - (exp(-t).*(2*cos(2*t) + sin(2*t)))/5)','t'); %y=2/5 - (exp(-x).*(2*cos(2*x) + sin(2*x)))/5; a=-0.5; for b=3:-15*0.005+0.000000001*randn:a plot(x,y(x),'LineWidth',2); hold on; plot(a, y(a),'k.','MarkerSize',18); plot(b, y(b),'k.','MarkerSize',18); m=(y(b)-y(a))/(b-a); yy=m*(x-a)+y(a); plot(x,yy,'LineWidth',1.5); axis([-1 3 min(y(x))-0.1 max(y(x))+0.1]); plot([a a],[-1.2 0],'k'); plot([b b],[-1.2 0],'k'); plot([a b],[-1 -1],'k'); plot([a b],[y(a) y(a)],'g--','LineWidth',1.5); plot([b b],[y(a) y(b)],'r--','LineWidth',1.5); if abs(b-a)>0.01 text((b+a)/2,-1.1,['$h\approx$',num2str(b-a)],'fontsize',20,'interpreter','latex'); text(-0.5,-1.34,['$\frac{\emph{rise}}{\emph{run}}=\frac{f(x+h)-f(x)}{h}\approx\,\, $',num2str(y(b)-y(a),3),'/',num2str(b-a,3)],'fontsize',20,'interpreter','latex'); text(2.2,-1.34,['$\approx\,\, $',num2str(m,3)],'fontsize',20,'interpreter','latex'); else text((b+a)/2,-1.1,'$h=0$','fontsize',20,'interpreter','latex'); text(-0.5,-1.34,['$\frac{\emph{rise}}{\emph{run}}=\frac{f(x+h)-f(x)}{h}\approx\,\, $',num2str(m,3)],'fontsize',20,'interpreter','latex'); end xlabel('$x$','fontsize',20,'interpreter','latex'); ylabel('$y$','fontsize',20,'interpreter','latex'); drawnow; hold off; % Capture the plot as an image frame = getframe(h); im = frame2im(frame); [imind,cm] = rgb2ind(im,256); % Write to the GIF File if b == 3 imwrite(imind,cm,filename,'gif', 'Loopcount',inf); else imwrite(imind,cm,filename,'gif','WriteMode','append'); end end