• No results found

MATLAB IMPLEMENTATION Direct FFT and Windowing

Spectral Analysis: Classical Methods

MATLAB IMPLEMENTATION Direct FFT and Windowing

MATLAB provides a variety of methods for calculating spectra, particularly if the Signal Processing Toolbox is available. The basic Fourier transform routine is implemented as:

X = fft(x,n)

TLFeBOOK

whereXis the input waveform andxis a complex vector providing the sinusoi-dal coefficients. The argumentnis optional and is used to modify the length of data analyzed: if n < length(x), then the analysis is performed over the first npoints; or, ifn > length(x), xis padded with trailing zeros to equaln. The fft routine implements Eq. (6) above and employs a high-speed algorithm.

Calculation time is highly dependent on data length and is fastest if the data length is a power of two, or if the length has many prime factors. For example, on one machine a 4096-point FFT takes 2.1 seconds, but requires 7 seconds if the sequence is 4095 points long, and 58 seconds if the sequence is for 4097 points. If at all possible, it is best to stick with data lengths that are powers of two.

The magnitude of the frequency spectra can be easily obtained by apply-ing the absolute value function,abs, to the complex outputX:

Magnitude = abs(X)

This MATLAB function simply takes the square root of the sum of the real part ofXsquared and the imaginary part ofXsquared. The phase angle of the spectra can be obtained by application of the MATLAB anglefunction:

Phase = angle(X)

Theanglefunction takes the arctangent of the imaginary part divided by the real part ofY. The magnitude and phase of the spectrum can then be plotted using standard MATLAB plotting routines. An example applying the MATLAB fftto a array containing sinusoids and white noise is provided below and the resultant spectra is given in Figure 3.10. Other applications are explored in the problem set at the end of this chapter. This example uses a special routine, sig_noise, found on the disk. The routine generates data consisting of sinu-soids and noise that are useful in evaluating spectral analysis algorithms. The calling structure forsig_noiseis:

[x,t] = sig_noise([f],[SNR],N);

where fspecifies the frequency of the sinusoid(s) in Hz,SNRspecifies the de-sired noise associated with the sinusoid(s) in db, andNis the number of points.

The routine assumes a sample frequency of 1 kHz. If fand SNR are vectors, multiple sinusoids are generated. The output waveform is in xandtis a time vector useful in plotting.

Example 3.1 Plot the power spectrum of a waveform consisting of a single sine wave and white noise with an SNR of −7 db.

TLFeBOOK

Spectral Analysis: Classical Methods 79

FIGURE3.10 Plot produced by the MATLAB program above. The peak at 250 Hz is apparent. The sampling frequency of this data is 1 kHz, hence the spectrum is symmetric about the Nyquist frequency, fs/2 (500 Hz). Normally only the first half of this spectrum would be plotted (SNR= −7 db; N = 1024).

% Example 3.1 and Figure 3.10 Determine the power spectrum

% of a noisy waveform

% First generates a waveform consisting of a single sine in

% noise, then calculates the power spectrum from the FFT

% and plots

clear all; close all;

N = 1024; % Number of data points

% Generate data using sig_noise

% 250 Hz sin plus white noise; N data points ; SNR = -7 db [x,t] = sig_noise (250,-7,N);

fs = 1000; % The sample frequency of data

% is 1 kHz.

Y = fft(x); % Calculate FFT

PS = abs(Y).v2; % Calculate PS as magnitude

% squared

TLFeBOOK

freq = (1:N)/fs; % Frequency vector for plot-ting

plot(freq,20*log10(PS),’k’); % Plot PS in log scale title(’Power Spectrum (note symmetric about fs/2)’);

xlabel(’Frequency (Hz)’);

ylabel(’Power Spectrum (db)’);

The Welch Method for Power Spectral Density Determination

As described above, the Welch method for evaluating the power spectrum di-vides the data in several segments, possibly overlapping, performs an FFT on each segment, computes the magnitude squared (i.e., power spectrum), then averages these spectra. Coding these in MATLAB is straightforward, but this is unnecessary as the Signal Processing Toolbox features a function that performs these operations. In its more general form, thepwelch* function is called as:

[PS,f] = pwelch(x,window,noverlap,nfft,fs)

Only the first input argument, the name of the data vector, is required as the other arguments have default values. By default, x is divided into eight sections with 50% overlap, each section is windowed with a Hamming window and eight periodograms are computed and averaged. If windowis an integer, it specifies the segment length, and a Hamming window of that length is applied to each segment. Ifwindowis a vector, then it is assumed to contain the window function (easily implemented using the window routines described below). In this situation, the window size will be equal to the length of the vector, usually set to be the same as nfft. If the window length is specified to be less than nfft (greater is not allowed), then the window is zero padded to have a length equal to nfft. The argument noverlapspecifies the overlap in samples. The sampling frequency is specified by the optional argumentfsand is used to fill the frequency vector,f, in the output with appropriate values. This output vari-able can be used in plotting to obtain a correctly scaled frequency axis (see Example 3.2). As is always the case in MATLAB, any variable can be omitted, and the default selected by entering an empty vector, [ ].

If pwelch is called with no output arguments, the default is to plot the power spectral estimate in dB per unit frequency in the current figure window.

IfPS is specified, then it contains the power spectra.PS is only half the length of the data vector, x, specifically, either (nfft/2)ⴙ1 if nfft is even, or (nfftⴙ1)/2fornfftodd, since the additional points would be redundant. (An

*The calling structure for this function is different in MATLAB versions less than 6.1. Use the

‘Help’ command to determine the calling structure if you are using an older version of MATLAB.

TLFeBOOK

Spectral Analysis: Classical Methods 81

exception is made ifxis complex data in which case the length ofPS is equal tonfft.) Other options are available and can be found in the help file forpwelch. Example 3.2 Apply Welch’s method to the sine plus noise data used in Example 3.1. Use 124-point data segments and a 50% overlap.

% Example 3.2 and Figure 3.11

% Apply Welch’s method to sin plus noise data of Figure 3.10 clear all; close all;

N = 1024; % Number of data points fs = 1000; % Sampling frequency (1 kHz)

FIGURE3.11 The application of the Welch power spectral method to data con-taining a single sine wave plus noise, the same as the one used to produce the spectrum of Figure 3.10. The segment length was 128 points and segments overlapped by 50%. A triangular window was applied. The improvement in the background spectra is obvious, although the 250 Hz peak is now broader.

TLFeBOOK

% Generate data (250 Hz sin plus noise) [x,t,] = sig_noise(250,-7,N);

%

% Estimate the Welch spectrum using 128 point segments,

% a the triangular filter, and a 50% overlap.

%

Comparing the spectra in Figure 3.11 with that of Figure 3.10 shows that the background noise is considerably smoother and reduced. The sine wave at 250 Hz is clearly seen, but the peak is now slightly broader indicating a loss in frequency resolution.

Window Functions

MATLAB has a number of data windows available including those de-scribed in Eqs. (11–13). The relevant MATLAB routine generates an n-point vector array containing the appropriate window shape. All have the same form:

w = window_name(N); % Generate vector w of length N

% containing the window function

% of the associated name

where Nis the number of points in the output vector and window_nameis the name, or an abbreviation of the name, of the desired window. At this writing, thirteen different windows are available in addition to rectangular (rectwin) which is included for completeness. Using help windowwill provide a list of window names. A few of the more popular windows are:bartlett,blackman, gausswin,hamming(a common MATLAB default window),hann,kaiser, and triang. A few of the routines have additional optional arguments. In particu-lar, chebwin (Chebyshev window), which features a nondecaying, constant level of sidelobes, has a second argument to specify the sidelobe amplitude. Of course, the smaller this level is set, the wider the mainlobe, and the poorer the frequency resolution. Details for any given window can be found through the helpcommand. In addition to the individual functions, all of the window func-tions can be constructed with one call:

w = window(@name,N,opt) % Get N-point window ‘name.’

TLFeBOOK

Spectral Analysis: Classical Methods 83

where name is the name of the specific window function (preceded by@),Nthe number of points desired, and opt possible optional argument(s) required by some specific windows.

To apply a window to the Fourier series analysis such as in Example 2.1, simply point-by-point multiply the digitized waveform by the output of the MATLABwindow_nameroutine before calling the FFT routine. For example:

w = triang (N); % Get N-point triangular window curve x = x .* w’; % Multiply (point-by-point) data by window X = fft(x); % Calculate FFT

Note that in the example above it was necessary to transpose the window functionWso that it was in the same format as the data. The window function produces a row vector.

Figure 3.12 shows two spectra obtained from a data set consisting of two sine waves closely spaced in frequency (235 Hz and 250 Hz) with added white noise in a 256 point array sampled at 1 kHz. Both spectra used the Welch method with the same parameters except for the windowing. (The window

func-FIGURE 3.12 Two spectra computed for a waveform consisting of two closely spaced sine waves (235 and 250 Hz) in noise (SNR= −10 db). Welch’s method was used for both methods with the same parameters (nfft= 128, overlap = 64) except for the window functions.

TLFeBOOK

tion can be embedded in thepwelchcalling structure.) The upper spectrum was obtained using a Hamming window (hamming) which has large sidelobes, but a fairly narrow mainlobe while the lower spectrum used a Chebyshev window (chebwin) which has small sidelobes but a larger mainlobe.

A small difference is seen in the ability to resolve the two peaks. The Hamming window with a smaller main lobe gives rise to a spectrum that shows two peaks while the presence of two peaks might be missed in the Chebyshev windowed spectrum.

PROBLEMS

1. (A) Construct two arrays of white noise: one 128 points in length and the other 1024 points in length. Take the FT of both. Does increasing the length improve the spectral estimate of white noise?

(B) Apply the Welch methods to the longer noise array using a Hanning window with an nfft of 128 with no overlap. Does this approach improve the spectral estimate? Now change the overlap to 64 and note any changes in the spectrum.

Submit all frequency plots appropriately labeled.

2. Find the power spectrum of the filtered noise data from Problem 3 in Chap-ter 2 using the standard FFT. Show frequency plots appropriately labeled. Scale, or rescale, the frequency axis to adequately show the frequency response of this filter.

3. Find the power spectrum of the filtered noise data in Problem 2 above using the FFT, but zero pad the data so that N= 2048. Note the visual improvement in resolution.

4. Repeat Problem 2 above using the data from Problem 6 in Chapter 2.

Applying the Hamming widow to the data before calculating the FFT.

5. Repeat problem 4 above using the Welch method with 256 and 65 segment lengths and the window of your choice.

6. Repeat Problem 4 above using the data from Problem 7, Chapter 2.

7. Use routine sig_noise noise to generate a 256-point array that contains two closely spaced sinusoids at 140 and 180 Hz both with an SNR of -10 db.

(Calling structure: data = sig_noise([140 180], [-10 -10], 256);) Sig_noiseassumes a sampling rate of 1 kHz. Use the Welch method. Find the spectrum of the waveform for segment lengths of 256 (no overlap) and 64 points with 0%, 50% and 99% overlap.

8. Usesig_noiseto generate a 512-point array that contains a single sinusoid at 200 Hz with an SNR of -12 db. Find the power spectrum first by taking the

TLFeBOOK

Spectral Analysis: Classical Methods 85

FFT of the autocorrelation function. Compare this power spectrum with the one obtained using the direct method. Plot the two spectra side-by-side.

9. Using the data of Problem 7 above, find the power spectrum applying the Welch method with 64-point segments, and no overlap. Using the Chebyshev (chebwin), Kaiser (kaiser), and Gauss (gausswin) windows, find the best window in terms of frequency separation. Submit frequency plots obtained using the best and worse windows (in terms of separation). For the Chebyshev win-dow use a ripple of 40 db, and for the Kaiser winwin-dow use a beta of 0 (minimum mainlobe option).

10. Use routinesig_noiseto generate a 512-point array containing one sinus-oid at 150 Hz and white noise; SNR= −15db. Generate the power spectrum as the square of the magnitude obtained using the Fourier transform. Put the signal generator commands and spectral analysis commands in a loop and calculate the spectrum five times plotting the five spectra superimposed. Repeat using the Welch method and data segment length of 128 and a 90% overlap.

TLFeBOOK

4