Derivative Operator Picture Code
The figure in Derivative Matrix for a Function Vector was generated with the following code:
<source lang="matlab">
%
% _-_,, ,, _-_- ,,
% ( // || /, _ ; || '
% _|| /'\\ ||/\\ \\/\\ || __ < \, \\/\/\ ||/\ \\ \\/\\ _-_,
% _|| || || || || || || ~||- - /-|| || | | ||_< || || || ||_.
% || || || || || || || ||===|| (( || || | | || | || || || ~ ||
% -__-, \\,/ \\ |/ \\ \\ ( \_, | \/\\ \\/\\/ \\,\ \\ \\ \\ ,-_-
% _/ `
%
% John Hawkins
% LNA
% Derivative Matrix Example
% 2 Feb 2010
function DerivativeExample
x=linspace(0,4*pi,500)';
y=sin(x);
dydx=cos(x);
h.fig=figure('color','w','units','normalized','position',[.2 .2 .6 .6]);
plot(x,y,'color',[.8 .8 .8]);
hold on;
plot(x,dydx,'color',[.8 .8 .8]);
numStartPoints=10;
x=linspace(0,4*pi,numStartPoints)';
y=sin(x);
dydx=DERIV(x,y);
h.y=plot(x,y,'b.');
h.construct=plot(0,0,'r');
h.dydx=plot(0,0,'r.');
legend([h.y,h.construct,h.dydx],'y','Construction Line','dy/dx');
xlabel('x'); ylabel('y');
axis equal;
title('Taking the Derivative of a Finite Function Vector for y=sin x',...
'fontname','times','fontsize',20);
set([h.construct,h.dydx],'visible','off');
fig = getframe(h.fig);
[im,map] = rgb2ind(fig.cdata,256,'nodither');
set(h.construct,'visible','on','xdata',x([1,2]),'ydata',y([1,2]));
im=CAPTUREFIG(im,map,h);
set(h.dydx,'visible','on','xdata',x(1),'ydata',dydx(1));
im=CAPTUREFIG(im,map,h);
for n=2:numStartPoints-1
set(h.construct,'xdata',x([n-1,n+1]),'ydata',y([n-1,n+1]));
im=CAPTUREFIG(im,map,h);
set(h.dydx,'xdata',x(1:n),'ydata',dydx(1:n));
im=CAPTUREFIG(im,map,h);
end
set(h.construct,'xdata',x([numStartPoints-1,numStartPoints]),...
'ydata',y([numStartPoints-1,numStartPoints]));
im=CAPTUREFIG(im,map,h);
set(h.dydx,'xdata',x,'ydata',dydx);
im=CAPTUREFIG(im,map,h);
set(h.construct,'visible','off');
im=CAPTUREFIG(im,map,h);
for k=1:5
im=CAPTUREFIG(im,map,h);
end
for n=[15 20 30 50 100 200 500]
x=linspace(0,4*pi,n)';
y=sin(x);
dydx=DERIV(x,y);
set(h.y,'xdata',x,'ydata',y);
set(h.dydx,'xdata',x,'ydata',dydx);
im=CAPTUREFIG(im,map,h);
end
for k=1:5
im=CAPTUREFIG(im,map,h);
end
imwrite(im,map,'Derivative.gif','DelayTime',.5,'LoopCount',inf)
function dydx=DERIV(x,y)
num=numel(y);
deltax=x(2)-x(1);
operator=zeros(num);
operator(1,1)=-2;
operator(1,2)=2;
for k=2:num-1
operator(k,k+1)=1;
operator(k,k-1)=-1;
end
operator(num,num-1)=-2;
operator(num,num)=2;
operator=operator/(2*deltax);
dydx=operator*y;
function im=CAPTUREFIG(im,map,h)
fig = getframe(h.fig);
im(:,:,1,size(im,4)+1) = rgb2ind(fig.cdata,map,'nodither');
</source>