% PSDemo.m illustrates convergence of periodic spectral method
% for derivative estimation of the periodic function y = exp(sin(t))
% Taken from Trefethen: Spectral Methods in Matlab

clear all
clc
close all
warning off
scrnsz = get(0, 'Screensize');

% For various N (even), set up grid as before:
figure('Position', [5 10 scrnsz(3)-5 scrnsz(4)-60])
for N = 2:2:100;
    h = 2*pi/N;
    t = -pi + (1:N)'*h;
    y = exp(sin(t)); yprime = cos(t).*y;

    % Construct spectral differentiation matrix:
    column = [0 .5*(-1).^(1:N-1).*cot((1:N-1)*h/2)];
    D = toeplitz(column,column([1 N:-1:2]))

    % Plot max(abs(D*y-yprime)):
    error = norm(D*y-yprime,inf);
    loglog(N,error,'.','markersize',15), hold on
end
grid on, xlabel N, ylabel error
title('Convergence of spectral differentiation')
hold off