create graph of a half-wave rectified sine in time and in frequency using the first seven fourier coefficients in matlab

main.m
% Define the frequencies and coefficients for the Fourier series
frequencies = [0 1 2 3 4 5 6 7]; %assuming the first 7 Fourier coefficients
coefficients = [0 2/(pi*1) 0 2/(3*pi) 0 2/(5*pi) 0 2/(7*pi)]; 

% Define the fundamental parameters
frequency = 1; % frequency of the sine wave
amplitude = max(coefficients); % amplitude of the sine wave

% Create the time vector
t = 0:0.001:2/frequency; % time from 0 to 2 periods

% Create the half-wave rectified sine wave
rectified_sine = zeros(size(t));
for n = 1:length(frequencies)
    rectified_sine = rectified_sine + coefficients(n)*sin(2*pi*frequencies(n)*frequency*t);
end
rectified_sine(rectified_sine < 0) = 0; % half-wave rectification

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

% Perform Fourier Transform
L = length(t); % Length of signal
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
fft_rectified_sine = fft(rectified_sine,NFFT)/L;
f = 1/(2*0.001)*linspace(0,1,NFFT/2+1);

% Plot single-sided amplitude spectrum.
subplot(2,1,2);
plot(f,2*abs(fft_rectified_sine(1:NFFT/2+1)));
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Half-Wave Rectified Sine Wave (Frequency Domain)');
1274 chars
38 lines

gistlibby LogSnag