half-wave sine plot in time and plot in frequency using only the first sevent fourier coefficients in matlab
main.m
% Generate a half-wave sine signalt = 0:0.001:1; % time vectorx = sin(2*pi*5*t); % sine wave signalN = 7; % number of Fourier coefficients to considerX_k = zeros(1,N); % Fourier coefficients vector% Calculate the Fourier coefficientsfor k = 1:N
X_k(k) = 2*trapz(t, x.*sin(2*pi*k*t));
end% Reconstruct the signal using the Fourier coefficientsx_rec = zeros(size(t));
for k = 1:N
x_rec = x_rec + X_k(k)*sin(2*pi*k*t);
end% Plot the original signal and the reconstructed signalfigure;
subplot(2,1,1);
plot(t, x);
title('Original Signal');
xlabel('Time');
ylabel('Amplitude');
subplot(2,1,2);
plot(t, x_rec);
title('Reconstructed Signal using First 7 Fourier Coefficients');
xlabel('Time');
ylabel('Amplitude');
% Calculate the frequency for each Fourier coefficientf_k = (1:N)/(t(end));
% Plot the Fourier coefficients in frequency domainfigure;
stem(f_k, abs(X_k), 'o'); % stem plot of Fourier coefficients magnitudestitle('Fourier Coefficients Magnitude vs Frequency');
xlabel('Frequency (Hz)');
ylabel('Magnitude');