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 signal
t = 0:0.001:1; % time vector
x = sin(2*pi*5*t); % sine wave signal

N = 7; % number of Fourier coefficients to consider
X_k = zeros(1,N); % Fourier coefficients vector

% Calculate the Fourier coefficients
for k = 1:N
    X_k(k) = 2*trapz(t, x.*sin(2*pi*k*t));
end

% Reconstruct the signal using the Fourier coefficients
x_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 signal
figure;
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 coefficient
f_k = (1:N)/(t(end));

% Plot the Fourier coefficients in frequency domain
figure;
stem(f_k, abs(X_k), 'o'); % stem plot of Fourier coefficients magnitudes
title('Fourier Coefficients Magnitude vs Frequency');
xlabel('Frequency (Hz)');
ylabel('Magnitude');
1043 chars
41 lines

gistlibby LogSnag