% Example taken from Chapter 4 of N. Trefethen's book 
% "Approximation Theory and Approximation Practice" (SIAM, 2013)

close all, clear all

format long

x = chebfun('x');
f = tanh(4*x-1);
n = 4; pn = chebfun(f,n+1);
fn = chebfun(f,'trunc',n+1);

figure(1)
hold off, plot(f), hold on, plot(pn,'.--r')
FS = 'fontsize';
plot(fn,'-.g')
title('Function f, interpolant p_4, projected approximant f_4',FS,9)
legend('f','p_4','f_4');


disp('The first 5 Chebyshev coefficients of f')

a = chebcoeffs(f); a = a(end:-1:1)'; a(1:n+1)


disp('The first 5 Chebyshev coefficients of p_n')

c = chebcoeffs(pn); c = c(end:-1:1)'

disp('Compute the interpolant coefficients from the Chebyshev coefficients')

c0 = sum(a(1:2*n:end))
for k = 1:n-1
  ck = sum(a(1+k:2*n:end)) + sum(a(1-k+2*n:2*n:end))
end
cn = sum(a(n+1:2*n:end))



figure(2)
hold off
subplot(2,1,1), plot(f-fn,'g'), ylim(.38*[-1 1])
title('Error in projection f-f_4',FS,9)
subplot(2,1,2), plot(f-pn,'r'), ylim(.38*[-1 1])
title('Error in interpolant f-p_4',FS,9)

figure(3)
n = 24; pn = chebfun(f,n+1);
fn = chebfun(f,'trunc',n+1);
subplot(2,1,1), plot(f-fn,'g'), ylim(.0005*[-1 1])
title('Error in projection f-f_{24}',FS,9)
subplot(2,1,2), plot(f-pn,'r'), ylim(.0005*[-1 1])
title('Error in interpolant f-p_{24}',FS,9)
