Using fft to plot frequency spectrum of sum of rectangular pulses
Ältere Kommentare anzeigen
fs = 10000;
t = -2:1/fs:2;
g_a = rectpuls(t/4) + rectpuls(t/2);
fn = fs/2;
f = linspace(-fn, fn, numel(t));
G_a = fft(g_a); % Fourier transform of function g_a
G_a_mag = abs(G_a);
subplot(2,1,1)
plot(t,g_a) % plot function wrt time
subplot(2,1,2)
plot(f, G_a_mag) % plot freq spectrum
axis([0 2 0 2])
Here is my code, I would like to obtain the correct plot for the frequency spectrum, but what I obtain is weird and wrong. By computing the result analytically, the Fourier transform should be the following : 2*sinc(omega) + 4*sinc(2*omega).
I can't figure out what I have done wrong, maybe I am not using the fft function correctly ?
Thank you for your help.
Akzeptierte Antwort
Weitere Antworten (1)
Scott MacKenzie
am 5 Mär. 2022
Bearbeitet: Scott MacKenzie
am 6 Mär. 2022
I think this is what you are after. Mostly, this code just follows the example in the fft documentation, particularly w.r.t. getting the single-sided frequency spectrum from the FFT. The top wavefrom is a square wave of period 4 seconds, or frequency 0.25 Hz. The bottom waveform is the frequency spectrum. The peaks are the harmonics of the square wave. These occur at 0.25 Hz, 0.75 Hz, 1.25 Hz, and 1.75 Hz, as expected. I'm not sure why the waveform is triangular. It might be because the fft function is only working with one cycle of the square wave.
fs = 10000;
t = -2:1/fs:2;
g_a = rectpuls(t/4) + rectpuls(t/2);
g_a(end) = 1; % fix last sample (was 0)
g_a = rescale(g_a, -1, 1); % remove dc offset in signal
G_a = fft(g_a); % Fourier transform of function g_a
% get frequency spectrum from G_a (see fft documenation)
n = numel(t)-1;
P2 = abs(G_a/n);
G_a_mag = P2(1:n/2+1);
G_a_mag(2:end-1) = 2*G_a_mag(2:end-1);
f = fs*(0:(n/2))/n;
subplot(2,1,1)
plot(t,g_a) % plot function wrt time
axis([-2 2 -1.5 1.5])
subplot(2,1,2)
plot(f, G_a_mag) % plot freq spectrum
axis([0 2 0 2])
1 Kommentar
Japhten
am 6 Mär. 2022
Kategorien
Mehr zu Spectral Measurements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

