---
title: 9-0. Chebyshev approximations - Coefficients
tags: Spectral method
---
**Textbook**
1. [Spectral method in Matlab](https://people.maths.ox.ac.uk/trefethen/spectral.html) by *Lloyd N. Trefethen*
2. [Finite difference and Spectral methods](https://people.maths.ox.ac.uk/trefethen/pdetext.html) by *Lloyd N. Trefethen*
3. A practical guide to pseudospectral method by *Bengt Fornberg*
---
## Examples in `Matlab`
### Example 1:
Consider $f(x) = x^5$, the corresponding Chebyshev coefficients are $f_k=[0, \frac{5}{8}, 0, \frac{5}{16}, 0, \frac{1}{16}]$
#### Method 1: `Matlab`
Chebyshev points of the second kind:
```Matlab=
% generate grid points
N = 5;
x = cos((0:N)*pi/N)';
% evaluate at grid points
f = x.^5;
% extend the function and take scaled FFT
f_extend = [f; f(N:-1:2)];
f_hat = fft(f_extend)/(2*N);
% obtain the Chebyshev coefficients
a = zeros(N+1,1);
a(1) = real(f_hat(1));
a(2:N) = 2*real(f_hat(2:N));
a(N+1) = real(f_hat(N+1));
% Clenshaw–Curtis weights
w = zeros(1,N+1);
if(mod(N,2)==0)
M = N/2;
else
M = (N-1)/2;
end
w(1:2:end) = 2./(1-4*(0:M).^2);
% Clenshaw–Curtis quadrature
w*a
```
##### Clenshaw–Curtis weights
```Matlab=
N=25;
w = zeros(1,N+1);
if(mod(N,2)==0)
M=N/2;
else
M = (N-1)/2;
end
w(1:2:end) = 2./(1-4*(0:M).^2);
w2 = [w, w(N:-1:2)];
CCW = ifft(w2');
CCW = [CCW(1), 2*CCW(2:N)', CCW(N+1)];
```
#### Method 2: `Matlab`
Chebyshev points of the second kind:
```Matlab=
% generate grid points
N = 5;
x = -sin((-N:2:N)'*pi/(2*N));
% evaluate at grid points
f = x.^5;
% extend the function and take scaled FFT
f_extend = [f; f(N:-1:2)];
f_hat = fft(f_extend)/(2*N);
% obtain the Chebyshev coefficients
a = zeros(N+1,1);
a(1) = real(f_hat(1));
a(2:N) = 2*real(f_hat(2:N));
a(N+1) = real(f_hat(N+1));
```
#### Method 2: `Julia`
Chebyshev points of the second kind:
```Julia=
# generate grid points
N = 5;
x = -sin.((-N:2:N)*pi/(2*N));
# evaluate at grid points
f = x.^5;
# extend the function and take scaled FFT
f_extend = [f; f[N:-1:2]];
f_hat = real(fft(f_extend)./(2*N));
# obtain the Chebyshev coefficients
a = zeros(N+1,1);
a[1] = real(f_hat[1]);
a[2:N] = 2*real(f_hat[2:N]);
a[N+1] = real(f_hat[N+1]);
```
#### Method 3: `Matlab`
Chebyshev points of the first kind using `dct`:
```Matlab=
% generate grid points
N = 5;
x = sin((N:-2:-N)'*pi/(2*(N+1)));
% evaluate at grid points
f = x.^5;
% Use DCT to obtain the Chebyshev coefficients
a = dct(f);
a(1) = a(1)/sqrt(N+1);
a(2:end)=a(2:end)/sqrt((N+1)/2);
```