% This code computes the fourier series of 
% f(x) =  { x for -pi<=x<=0
%         { 0 for 0<=x<pi

%N is the number of terms you want to take in the series
N = 20;

% x is the interval over which you want to plot the partial sum
x = [-pi+1e-2:0.05:pi-1e-2];

% make a vector with exact solution
f = zeros(size(x));
lenx = length(x);
f(1:lenx/2) = x(1:lenx/2);


a0 = -pi/2;

%fs is the partial fourier series

fs = a0/2*ones(size(x));
for n = 1:N
    fs = fs + 2*cos((2*n-1)*x)/(pi*(2*n-1)^2)+(-1)^(n+1)/n*sin(n*x);
end
figure(1)
plot(x,fs,'b',x,f,'k')


% err = abs(f-fs);
% figure(2)
% plot(x,err)

x2 = [-3*pi:0.05:3*pi];
fs2 = a0/2*ones(size(x2));
for n = 1:N
    fs2 = fs2 + 2*cos((2*n-1)*x2)/(pi*(2*n-1)^2)+(-1)^(n+1)/n*sin(n*x2);
end
figure(2)
plot(x2,fs2,'b',x,f,'k')
