create plots of an half-wave rectified sine both in time and in frequency using the first seven fourier coefficients only in matlab

main.m
% Time domain plot of half-wave rectified sine wave
f = 1; % Frequency of the sine wave
t = 0:0.001:2; % Time range

x = abs(sin(2*pi*f*t)); % Half-wave rectified sine wave

figure;
plot(t, x);
title('Half-wave rectified sine wave in Time domain');
xlabel('Time');
ylabel('Amplitude');

% Fourier series representation of half-wave rectified sine wave
n = 1:7; % First seven Fourier coefficients
a = 4/pi * (1./n); % Compute Fourier coefficients

N = 500; % Number of samples for frequency domain plot
fs = N/(t(end)-t(1)); % Sampling frequency

frequencies = (-N/2:N/2-1)*fs/N; % Frequency axis
X = zeros(size(frequencies));

for i = 1:length(a)
    X = X + a(i) * sinc(frequencies*i); % Amplitude spectrum using Fourier coefficients
end

figure;
plot(frequencies, abs(X));
title('Half-wave rectified sine wave in Frequency domain');
xlabel('Frequency');
ylabel('Magnitude');
877 chars
32 lines

gistlibby LogSnag