% SpectralDiffDemo.m illustrates periodic spectral differentiation
% for 2 different functions (one smooth, the other not)
% Based on Trefethen: Spectral Methods in Matlab

clear all
clc
close all
scrnsz = get(0, 'Screensize');
figure('Position', [5 10 scrnsz(3)-5 scrnsz(4)-60])

% Set up grid and differentiation matrix:
N = 24; h = 2*pi/N; t = h*(1:N)';
column = [0 .5*(-1).^(1:N-1).*cot((1:N-1)*h/2)]';
D = toeplitz(column,column([1 N:-1:2]));

% Differentiation of a hat function:
y = max(0,1-abs(t-pi)/2); clf
subplot(2,2,1), plot(t,y,'.-','markersize',13)
axis([0 2*pi -.5 1.5]), grid on, title('function')
subplot(2,2,2), plot(t,D*y,'.-','markersize',13)
axis([0 2*pi -1 1]), grid on, title('spectral derivative')

% Differentiation of exp(sin(x)):
y = exp(sin(t)); yprime = cos(t).*y;
subplot(2,2,3), plot(t,y,'.-','markersize',13)
axis([0 2*pi 0 3]), grid on
subplot(2,2,4), plot(t,D*y,'.-','markersize',13)
axis([0 2*pi -2 2]), grid on
error = norm(D*y-yprime,inf);
text(2.2,1.4,['max error = ' num2str(error)])
