create half-wave sine plots in time and in frequency with fourier coefficients in matlab in matlab
main.m
% Creating a half-wave sine signalt = 0:0.001:1; % Time vector from 0 to 1 seconds with 0.001 sec incrementf = 5; % Frequency of the sine wavex = sin(2*pi*f*t).*(sin(2*pi*f*t)>0); % Half-wave sine signal% Plotting the half-wave sine signal in time domainfigure;
subplot(2,1,1);
plot(t,x);
xlabel('Time (s)');
ylabel('Amplitude');
title('Half-wave Sine Signal in Time Domain');
% Computing Fourier series coefficientsN = 10; % Number of coefficientsa = zeros(1,N);
b = zeros(1,N);
a(1) = 2/pi; % DC componentfor n = 1:N
a(n+1) = 0;
b(n+1) = (2/(n*pi))*(1-(-1)^n)/2; % Coefficients formulaend% Plotting the frequency spectrumf0 = 1/(t(2)-t(1)); % Sampling frequencyfHz = 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');