create half-rectified sine plots both in time and in frequency with first seven fourier coefficients in matlab

main.m
% Define the time vector
t = 0:0.001:2*pi;

% Generate the half-rectified sine signal
x = sin(t);
x(x<0) = 0;

% Calculate the Fourier coefficients using FFT
X = fft(x);
n = 7; % number of coefficients to keep

% Shift zero frequency component to the center
X = fftshift(X);

% Zero out the coefficients beyond n
X(1:ceil(end/2)-n/2) = 0;
X(ceil(end/2)+n/2+1:end) = 0;

% Shift zero frequency component back
X = ifftshift(X);

% Reconstruct the signal using the inverse FFT
x_reconstructed = ifft(X);

% Plot the time domain signal
subplot(2,1,1);
plot(t,x_reconstructed);
title('Half Rectified Sine Wave in Time Domain');
xlabel('Time');
ylabel('Amplitude');

% Plot the frequency domain signal
f = (-length(t)/2:length(t)/2-1)/(length(t)/(2*pi));
subplot(2,1,2);
plot(f, abs(X));
title('Half Rectified Sine Wave in Frequency Domain');
xlabel('Frequency');
ylabel('Magnitude');
879 chars
39 lines

related categories

gistlibby LogSnag