MATLAB: Plotting the frequency spectrum / didnt understand the code

frequency/spectrum/understanding

X_mags = abs(fftshift(fft(signal)));
bin_vals = [0 : N-1];
N_2 = ceil(N/2);
fax_Hz = (bin_vals-N_2)*fs/N;
plot(fax_Hz, X_mags)

Best Answer

Qusay - let us assume the following concerning your signal, sampling rate (Fs), and FFT block size (N)
Fs = 4096; % sampling rate in Hertz
t = linspace(0,1-1/Fs,Fs); % one second time vector given Fs
N = 4096; % FFT block size is same as sampling rate (true for your ex)
signal = 2.3*sin(2*pi*t*227); % signal with amplitude of 2.3 and frequency of 227 Hertz
Now for your code
% transforms the signal from the time domain to the frequency domain with fft
% note that y is complex
Y = fft(signal);
% shifts the frequency components so that the zero frequency is at the centre
% of spectrum
Y = fftshift(Y);
% determines the magnitude of the complex data
Y = abs(Y);
The following lines of code just sets the frequencies for each bin and can be reduced to
f = [0:N-1] * Fs/N;
% must ensure that zero is the centre frequency due to our fftshift from above
f = f - ceil(N/2);
% plot the data
plot(f,Y);
The result of the plot is
Note the frequency at 227 Hz, as expected. The symmetry is due to the input signal being real.