fourier series for odd triangle function in matlab

To plot the Fourier series for an odd triangle wave function in MATLAB, you can follow these steps:

  1. Define the triangle wave function using a combination of the sawtooth and abs functions. Since we want an odd triangle wave function, we can use the sawtooth function with a period of pi and a phase of -pi/2, and take the absolute value of the result. Here is an example implementation:
main.m
% Define triangle wave with period 2*pi
period = 2*pi;
triangle = @(t) abs(sawtooth(t - pi/2, 0.5));

% Plot the triangle wave from -2*pi to 2*pi
t = linspace(-2*pi, 2*pi, 1000);
plot(t, triangle(t));
xlim([-2*pi, 2*pi]);
ylim([-0.2, 1.2]);
xlabel('t');
ylabel('f(t)');
270 chars
12 lines
  1. Define the Fourier coefficients for the triangle wave. Since the triangle wave is odd, the Fourier series only includes sine terms. The nth coefficient can be calculated using the formula:
main.m
B_n = (2/period) * integral(f(t) * sin(n * pi * t / period), t, -period/2, period/2)
85 chars
2 lines

In the case of the odd triangle wave function, we can use the formula for the Fourier series of a sawtooth wave:

main.m
B_n = (-1)^{n+1} * (2/(n * pi))
32 chars
2 lines

Here is an example implementation:

main.m
% Define Fourier series coefficients
n_max = 10;
B = zeros(1, n_max);
for n = 1:n_max
    B(n) = (-1)^(n+1) * (2/(n * pi));
end
128 chars
7 lines
  1. Calculate the Fourier series for the triangle wave. We can use a loop to iteratively add up each sine term in the series using the Fourier coefficients. Here is an example implementation:
main.m
% Calculate Fourier series
y = zeros(size(t));
for n = 1:n_max
    y = y + B(n) * sin(n * t);
end

% Plot Fourier series
hold on;
plot(t, y);
legend({'Triangle wave', 'Fourier series (n=10)'});
194 chars
11 lines

Here's the full code:

main.m
% Define triangle wave with period 2*pi
period = 2*pi;
triangle = @(t) abs(sawtooth(t - pi/2, 0.5));

% Plot the triangle wave from -2*pi to 2*pi
t = linspace(-2*pi, 2*pi, 1000);
plot(t, triangle(t));
xlim([-2*pi, 2*pi]);
ylim([-0.2, 1.2]);
xlabel('t');
ylabel('f(t)');
hold on;

% Define Fourier series coefficients
n_max = 10;
B = zeros(1, n_max);
for n = 1:n_max
    B(n) = (-1)^(n+1) * (2/(n * pi));
end

% Calculate Fourier series
y = zeros(size(t));
for n = 1:n_max
    y = y + B(n) * sin(n * t);
end

% Plot Fourier series
plot(t, y);
legend({'Triangle wave', 'Fourier series (n=10)'});
594 chars
30 lines

gistlibby LogSnag