Fourier sine series: sawtooth wave

Math 331, Fall 2017, Lecture 2, (c) Victor Matveev

Fourier series of a simple linear function f(x)=x converges to an odd periodic extension of this function, which is a saw-tooth wave.

hold off
L     = 1;                        % Length of the interval
x     = linspace(-3*L, 3*L, 300); % Create 300 points on the interval [-3L, 3L]
Const = -2*L/pi;                  % Constant factor in the expression for B_n
Sn    = 0;                        % Initialize vector sum series to zero

for n = 1 : 3
    Const = -Const;               % Efficient way to implement alternating sign
    Bn = Const/n;                 % Coefficients inversely proportional to n
    Fn = Bn * sin(n*pi*x);        % Calculate Fourier term
    Sn = Sn + Fn;                 % Add the term to Fourier sum
    plot(x, Sn, 'linewidth', n/2); % Plot the fourier sum
    hold on;

xlabel('x'); ylabel('Sum(B_nsin(n\pix))');
title('Sum of first few terms in the sine series B_nsin(n\pix) (L=1)');
plot(x, mod(x+1,2)-1,  'k-', 'linewidth', 1.5) % Tricky part of the code: generate saw-tooth wave
legend('B_1sin(\pix)', 'B_1sin(\pix/L)+B_2sin(2\pix)', 'B_1sin(\pix)+B_2sin(2\pix)+B_3sin(3\pix)', 'f(x) (odd extension)', 'Location', 'Southeast');