Hello Mr. Santa
I went through the shared code and suggest the following changes:
- Define a sawtooth-like waveform, where x(t) = 0 from t = 0 to 1, then rises to 1 and linearly drops from 1 to 0 in the interval t = 1 to 2. This pattern repeats with period T = 2 using the mod function for periodicity.
- Use a finely sampled time vector (-3:0.01:3) instead of discrete time points, in order to make the plot more smoother.
- Remove the square function.
- Calculate correct Fourier coefficients by integrating the expression (2 - t) over [1, 2], where the signal is non-zero.
- Clean up the loop to compute the Fourier sum using:
- F = a0/2 + ∑ [aₙ cos(nω₀t) + bₙ sin(nω₀t)]
Please refer to the following code for better understanding:
% Define the time vector and signal for the sawtooth-like wave
t = -3:0.01:3; % Fine resolution for smooth plotting
T = 2; % Period of the signal
xt = zeros(size(t)); % Initialize the signal
for i = 1:length(t)
t_mod = mod(t(i), T); % Map time to one period [0, T]
if t_mod >= 1 && t_mod <= 2
xt(i) = 2 - t_mod; % Linear decrease from 1 to 0 over t=1 to t=2
end
end
% Plot the original signal
subplot(2,1,1)
plot(t, xt, 'LineWidth', 1.5)
title('Graph of the Original Signal')
xlabel('Time, t')
ylabel('Amplitude, x(t)')
grid on
axis([-3 3 -0.2 1.2])
% Fourier Series Calculation
w0 = 2 * pi / T; % Fundamental frequency
N = 5; % Number of harmonics
k = -3:0.01:3; % Time vector for Fourier series
F = zeros(size(k)); % Initialize Fourier series output
% Compute a0 (DC component)
syms t
a0 = (2/T) * int(2-t, t, 1, 2); % Integrate over [1,2] where signal is non-zero
a0 = double(a0); % Convert to numerical value
F = F + a0 / 2; % Add DC component
% Compute an and bn coefficients
for n = 1:N
an = (2/T) * int((2-t) * cos(n*w0*t), t, 1, 2); % Integrate over [1,2]
bn = (2/T) * int((2-t) * sin(n*w0*t), t, 1, 2); % Integrate over [1,2]
an = double(an); % Convert to numerical
bn = double(bn); % Convert to numerical
F = F + an * cos(n*w0*k) + bn * sin(n*w0*k); % Add nth harmonic
end
% Plot the Fourier series
subplot(2,1,2)
plot(k, F, 'LineWidth', 1.5)
title('Graph of the Fourier Series Signal in Trigonometric Form')
xlabel('Time, t')
ylabel('Amplitude, x(t)')
grid on
axis([-3 3 -0.2 1.2])