The general explain of Fourier series is in the follwoing link:
https://zh.wikipedia.org/wiki/%E5%82%85%E9%87%8C%E5%8F%B6%E7%BA%A7%E6%95%B0
I am not sure your question is, since f(x) = [empty]^2 !?
So I assumed that your question is related to x^2 in the domain of [-pi, pi], the re-written question is shown below.
The code is:
clear all
figure
for nmax = 2:2:20
x = -2:.01:2;
a0 = pi^2/3;
fn = a0;
plot(x,x.^2,'linewidth',2,'color',[0 0 0]+.8)
axis([-3 3 0 4]), grid on, hold on
for n = 1:1:nmax
an = (-1)^n*4/n^2*cos(n*x);
fn = fn + an;
end
plot(x,fn,'linewidth',2,'color','k')
axis([-3 3 0 4]), grid on, pause(1)
hold off
end
The output of this code is