The typical function for calculating spectra is pwelch
from the signal processing toolbox. Typical usage is:
[PSD_x, F] = pwelch(x, hann(nfft), nfft/2, nfft, fsample);
loglog(F, PSD_x)
This gives you a statistically correct estimate of the real PSD, which a standard FFT does not give you. It works by dividing your data x
into several windows of length nfft
, applies a proper window function and then calculates the average of the FFTs of all the windows, with proper scaling. Since these windows are usually close to zero at their ends, you typically use half-overlapping windows (this is the third argument nfft/2
) so that all data is used more or less equally. The units in output are amplitude squared per hertz, so if x
is a voltage, the units are V^2/Hz
. In some fields it is more common to plot the linear spectral density, which simply the square root of the PSD, which in this case would be in V/sqrt(Hz)
.
Choosing the right value of nfft
is bit of an art, but this can be understood using the following equations: If the number of averages is navg
, the total time of your data is t_total = t_window * (navg + 1) / 2 ~= navg * t_window / 2
, where t_window
is the time of a single fourier window, and nfft = t_window * fsample
. The obtained frequency resolution df
is simply the inverse of the window length: df = 1 / t_window
.
Using these equations, you can find relations between 3 important properties: the number of averages navg
, which you typically want to be between 10 and 50 or so, the frequency resolution df
, which should follow from the typical frequencies of your problem, and t_total
, which determines the total amount of data that you either have available or that you should measure. If you know 2 out of these 3 properties, the third one follows.