create half-rectified sine plots both in time and in frequency using fourier coefficients in matlab

main.m
% Define time vector
t = 0:0.01:10;
fs = 100;

% Calculate Fourier coefficients
n = 50; % Number of harmonics
A0 = 0; % DC offset
A = zeros(1,n);
B = zeros(1,n);

for i = 1:n
    A(i) = 0; % Set to 0 for half-wave rectification
    if mod(i,2) == 1
        B(i) = 4/(i*pi); % Amplitude of the i-th harmonic
    else
        B(i) = 0;
    end
end

% Generate the half-rectified sine wave in time domain
xt = A0/2 + sum(A .* cos(2*pi*([1:n])*fs.'.*t/fs) + B .* sin(2*pi*([1:n])*fs.'.*t/fs), 2);

% Compute the Fourier Transform
f = (-fs/2:1:(fs/2-1));
Xf = zeros(size(f));

for i = 1:n
    Xf = Xf + A(i)*sinc(f - i*fs) + B(i)*(j*0.5*(dirac((f+i*fs)/fs) - dirac((f-i*fs)/fs)));
end

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

% Plot the frequency domain signal
subplot(2,1,2)
stem(f, abs(Xf))
title('Frequency Spectrum of Half Rectified Sine Wave')
xlabel('Frequency (Hz)')
ylabel('Magnitude')

996 chars
45 lines

This code defines a half-rectified sine wave in the time domain using Fourier coefficients and plots both the time and frequency domain representations of the signal.

gistlibby LogSnag