% Spectral differentiation using the differentiation matrix

  N = 24;  h = 2*pi/N; x = h*(1:N)';
  col = [0 0.5*(-1) .^ (1:N-1) .* cot((1:N-1)*h/2)]';
  D = toeplitz(col, col([1 N:-1:2]));

% Hat function

  v = max(0, 1-abs(x-pi)/2);
  subplot(2,2,1), plot(x, v, '.', 'markersize', 13);
  axis([0 2*pi -0.5 1.5]), grid on, title('function');
  subplot(2,2,2), plot(x, D*v, '.-', 'markersize', 13);
  axis([0 2*pi -1 1]), grid on, title('spectral derivative');

% v = exp(sin(x))

  v = exp(sin(x));  vprime = cos(x) .* v;
  subplot(2,2,3), plot(x, v, '.', 'markersize', 13);
  axis([0 2*pi 0 3]), grid on
  subplot(2,2,4), plot(x, D*v, '.-', 'markersize', 13);
  axis([0 2*pi -2 2]), grid on
  err = norm(D*v-vprime, inf);
  text(1.5, 1.4, ['max error = ' num2str(err)]);
