function m20121125_06_DemoOfIntegrationAndDifferentiationInV() % Demonstration of spectral differentiation and integration on a fixed grid % suited for functions that behave roughly like exp(-x^2) for large x, i.e. % functions resembling a Maxwellian distribution function. % % Written by Matt Landreman, July 6, 2012 % Number of grid points: N = 7; % Amount by which to scale all the grid points: scale = 1; %pointAtZero = true; pointAtZero = false; % Additional power of x to include in weight: k=0; %----------------------------------- % End of input parameters %----------------------------------- [x,ddx,d2dx2,weights] = m20130312_02_SpectralNodesWeightsAndDifferentiationMatricesForV(N, k, scale, pointAtZero); scrsz = get(0,'ScreenSize'); figure('Position',[0.2*scrsz(3), 0.1*scrsz(4), 0.4*scrsz(3),0.8*scrsz(4)]) clf numRows=3; numCols=1; subplot(numRows,numCols,1) xFine = linspace(0,max(x)*1.1,50); plot(xFine,f(xFine)) hold on plot(x,f(x),'.r') xlabel('x') title('f(x)') subplot(numRows,numCols,2) plot(xFine,dfdx(xFine)) hold on plot(x,ddx*f(x),'.r') xlabel('x') title('df/dx') legend('exact','differentiation matrix') subplot(numRows,numCols,3) semilogy(x,abs(dfdx(x)-ddx*f(x)),'.-r') xlabel('x') title('error in df/dx') directIntegration = quadgk(@f,0,Inf); integrationOnOurFixedGrid = weights' * f(x); s1=sprintf('%.15g\n',directIntegration); s2=sprintf('%.15g\n',integrationOnOurFixedGrid); annotation(gcf,'textbox', [0.57, 0.88, 0.38, 0.10],'String',{'Direct integral:',s1,'Integral using our fixed grid:',s2},'FitBoxToText','on','Background','w'); end function ff=f(x) % This function may be any function that behaves roughly like exp(-x^2) % for large x. ff = x.*exp(-x.*x).*sin(x-1); end function ff=dfdx(x) % This should return the analytic derivative of the previous function ff = ((1-2*x.*x).*sin(x-1) + x.*cos(x-1)) .* exp(-x.*x); end