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

To create a half-rectified sine plot in time and frequency domain with Fourier coefficients in MATLAB, you can follow these steps:

main.m
% Define parameters
f = 1; % Frequency of the sine wave
T = 1; % Time period
fs = 1000; % Sampling frequency
t = 0:1/fs:T; % Time vector
n = 10; % Number of harmonics

% Generate half-rectified sine wave
x = sin(2*pi*f*t);
x(x<0) = 0; % Half rectification

% Plot the half-rectified sine wave in time domain
figure;
subplot(2,1,1);
plot(t, x);
xlabel('Time (s)');
ylabel('Amplitude');
title('Half-Rectified Sine Wave in Time Domain');

% Compute Fourier coefficients
A = zeros(1, n);
B = zeros(1, n);

for k = 1:n
    A(k) = 2/T * trapz(t, x .* cos(2*pi*k*f*t));
    B(k) = 2/T * trapz(t, x .* sin(2*pi*k*f*t));
end

% Generate frequency domain representation
f_axis = (0:n-1)*(f/T);
Xf = A(1)/2 + zeros(size(f_axis)); % DC component

for k = 1:n
    Xf = Xf + A(k)*cos(2*pi*k*f*f_axis*T) + B(k)*sin(2*pi*k*f*f_axis*T);
end

% Plot the Fourier series representation in frequency domain
subplot(2,1,2);
stem(f_axis, abs(Xf));
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Fourier Series representation of the Half-Rectified Sine Wave');

1045 chars
44 lines

This code snippet will create and plot a half-rectified sine wave in both time and frequency domains along with its Fourier coefficients. Adjust parameters like frequency, time period, sampling frequency, and the number of harmonics as needed.

gistlibby LogSnag