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

main.m
% Creating a half-wave sine signal
t = 0:0.001:1; % Time vector from 0 to 1 seconds with 0.001 sec increment
f = 5; % Frequency of the sine wave
x = sin(2*pi*f*t).*(sin(2*pi*f*t)>0); % Half-wave sine signal

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

% Computing Fourier series coefficients
N = 10; % Number of coefficients
a = zeros(1,N);
b = zeros(1,N);
a(1) = 2/pi; % DC component
for n = 1:N
    a(n+1) = 0;
    b(n+1) = (2/(n*pi))*(1-(-1)^n)/2; % Coefficients formula
end

% Plotting the frequency spectrum
f0 = 1/(t(2)-t(1)); % Sampling frequency
fHz = linspace(-f0/2, f0/2, length(t));
X = a(1)/2 + sum(a(2:N+1)'*cos(2*pi*f*(1:N)'*t) + b(2:N+1)'*sin(2*pi*f*(1:N)'*t));

subplot(2,1,2);
plot(fHz, abs(fftshift(fft(X))));
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Frequency Spectrum of Half-wave Sine Signal');
961 chars
34 lines

gistlibby LogSnag