Time–Frequency Analysis
MATLAB IMPLEMENTATION The Short-Term Fourier Transform
The implementation of the time–frequency algorithms described above is straight-forward and is illustrated in the examples below. The spectrogram can be gener-ated using the standardfftfunction described in Chapter 3, or using a special function of the Signal Processing Toolbox,specgram. The arguments for spec-gram (given on the next page) are similar to those use forpwelchdescribed in Chapter 3, although the order is different.
TLFeBOOK
Time–Frequency Analysis 157
[B,f,t] = specgram(x,nfft,fs,window,noverlap)
where the output,B, is a complex matrix containing the magnitude and phase of the STFT time–frequency spectrum with the rows encoding the time axis and the columns representing the frequency axis. The optional output arguments,f andt, are time and frequency vectors that can be helpful in plotting. The input arguments include the data vector,x, and the size of the Fourier transform win-dow,nfft. Three optional input arguments include the sampling frequency,fs, used to calculate the plotting vectors, the window function desired, and the number of overlapping points between the windows. The window function is specified as in pwelch: if a scalar is given, then a Hanning window of that length is used.
The output of all MATLAB-based time–frequency methods is a function of two variables, time and frequency, and requires either a three-dimensional plot or a two-dimensional contour plot. Both plotting approaches are available through MATLAB standard graphics and are illustrated in the example below.
Example 6.1 Construct a time series consisting of two sequential sinu-soids of 10 and 40 Hz, each active for 0.5 sec (see Figure 6.2). The sinusinu-soids should be preceded and followed by 0.5 sec of no signal (i.e., zeros). Determine the magnitude of the STFT and plot as both a three-dimensional grid plot and as a contour plot. Do not use the Signal Processing Toolbox routine, but develop code for the STFT. Use a Hanning window to isolate data segments.
Example 6.1 uses a function similar to MATLAB’sspecgram, except that the window is fixed (Hanning) and all of the input arguments must be specified.
This function,spectog, has arguments similar to those inspecgram. The code for this routine is given below the main program.
FIGURE6.2 Waveform used in Example 6.1 consisting of two sequential sinu-soids of 10 and 40 Hz. Only a portion of the 0.5 sec endpoints are shown.
TLFeBOOK
% Example 6.1 and Figures 6.2, 6.3, and 6.4
% Example of the use of the spectrogram
% Uses function spectog given below
%
clear all; close all;
% Set up constants
fs = 500; % Sample frequency in Hz N = 1024; % Signal length
f1 = 10; % First frequency in Hz f2 = 40; % Second frequency in Hz nfft = 64; % Window size
noverlap = 32; % Number of overlapping points (50%)
%
% Construct a step change in frequency
tn = (1:N/4)/fs; % Time vector used to create sinusoids x = [zeros(N/4,1); sin(2*pi*f1*tn)’; sin(2*pi*f2*tn)’...
zeros(N/4,1)];
t = (1:N)/fs; % Time vector used to plot plot(t,x,’k’);
....labels....
% Could use the routine specgram from the MATLAB Signal Processing
% Toolbox: [B,f,t] = specgram(x,nfft,fs,window,noverlap),
% but in this example, use the “spectog” function shown below.
FIGURE6.3 Contour plot of the STFT of two sequential sinusoids. Note the broad time and frequency range produced by this time–frequency approach. The ap-pearance of energy at times and frequencies where no energy exists in the origi-nal sigorigi-nal is evident.
TLFeBOOK
Time–Frequency Analysis 159
FIGURE6.4 Time–frequency magnitude plot of the waveform in Figure 6.3 using the three-dimensional grid technique.
%
[B,f,t] = spectog(x,nfft,fs,noverlap);
B = abs(B); % Get spectrum magnitude figure;
mesh(t,f,B); % Plot Spectrogram as 3-D mesh view(160,40); % Change 3-D plot view
axis([0 2 0 100 0 20]); % Example of axis and xlabel(’Time (sec)’); % labels for 3-D plots ylabel(’Frequency (Hz)’);
figure
contour(t,f,B); % Plot spectrogram as contour plot ....labels and axis....
The functionspectogis coded as:
function [sp,f,t] = spectog(x,nfft,fs,noverlap);
% Function to calculate spectrogram
TLFeBOOK
% Output arguments
% sp spectrogram
% t time vector for plotting
% f frequency vector for plotting
% Input arguments
% x data
% nfft window size
% fs sample frequency
% noverlap number of overlapping points in adjacent segments
% Uses Hanning window
incr = nfft—noverlap; % Calculate window increment hwin = fix(nfft/2); % Half window size
f = (1:hwin)*(fs/nfft); % Calculate frequency vector
% Zero pad data array to handle edge effects x_mod = [zeros(hwin,1); x; zeros(hwin,1)];
%
j = 1; % Used to index time vector
% Calculate spectra for each window position
% Apply Hanning window for i = 1:incr:N
data = x_mod(i:iⴙnfft-1) .* hanning(nfft);
ft = abs(fft(data)); % Magnitude data
sp(:,j) = ft(1:hwin); % Limit spectrum to meaningful
% points
t(j) = i/fs; % Calculate time vector j = j ⴙ 1; % Increment index end
Figures 6.3 and 6.4 show that the STFT produces a time–frequency plot with the step change in frequency at approximately the correct time, although neither the step change nor the frequencies are very precisely defined. The lack of finite support in either time or frequency is evidenced by the appearance of energy slightly before 0.5 sec and slightly after 1.5 sec, and energies at frequen-cies other than 10 and 40 Hz. In this example, the time resolution is better than the frequency resolution. By changing the time window, the compromise be-tween time and frequency resolution could be altered. Exploration of this trade-off is given as a problem at the end of this chapter.
A popular signal used to explore the behavior of time–frequency methods is a sinusoid that increases in frequency over time. This signal is called a chirp
TLFeBOOK
Time–Frequency Analysis 161
signal because of the sound it makes if treated as an audio signal. A sample of such a signal is shown in Figure 6.5. This signal can be generated by multiplying the argument of a sine function by a linearly increasing term, as shown in Exam-ple 6.2 below. Alternatively, the Signal Processing Toolbox contains a special function to generate a chip that provides some extra features such as logarithmic or quadratic changes in frequency. The MATLAB chirp routine is used in a latter example. The output of the STFT to a chirp signal is demonstrated in Figure 6.6.
Example 6.2 Generate a linearly increasing sine wave that varies be-tween 10 and 200 Hz over a 1sec period. Analyze this chirp signal using the STFT program used in Example 6.1. Plot the resulting spectrogram as both a 3-D grid and as a contour plot. Assume a sample frequency of 500 Hz.
% Example 6.2 and Figure 6.6
% Example to generate a sine wave with a linear change in frequency
% Evaluate the time–frequency characteristic using the STFT
% Sine wave should vary between 10 and 200 Hz over a 1.0 sec period
% Assume a sample rate of 500 Hz
%
clear all; close all;
% Constants
N = 512; % Number of points
FIGURE6.5 Segment of a chirp signal, a signal that contains a single sinusoid that changes frequency over time. In this case, signal frequency increases linearly with time.
TLFeBOOK
FIGURE6.6 The STFT of a chirp signal, a signal linearly increasing in frequency from 10 to 200 Hz, shown as both a 3-D grid and a contour plot.
fs = 500; % Sample freq;
f1 = 10; % Minimum frequency
f2 = 200; % Maximum frequency
nfft = 32; % Window size
t = (1:N)/fs; % Generate a time
% vector for chirp
% Generate chirp signal (use a linear change in freq) fc = ((1:N)*((f2-f1)/N)) ⴙ f1;
x = sin(pi*t.*fc);
%
% Compute spectrogram using the Hanning window and 50% overlap [B,f,t] = spectog(x,nfft,fs,nfft/2); % Code shown above
%
subplot(1,2,1); % Plot 3-D and contour
% side-by-side
mesh(t,f,abs(B)); % 3-D plot
....labels, axis, and title....
subplot(1,2,2);
contour(t,f,abs(B)); % Contour plot ....labels, axis, and title....
The Wigner-Ville Distribution
The Wigner-Ville distribution will provide a much more definitive picture of the time–frequency characteristics, but will also produce cross products: time–
TLFeBOOK
Time–Frequency Analysis 163
frequency energy that is not in the original signal, although it does fall within the time and frequency boundaries of the signal. Example 6.3 demonstrates these properties on a signal that changes frequency abruptly, the same signal used in Example 6.1with the STFT. This will allow a direct comparison of the two methods.
Example 6.3 Apply the Wigner-Ville distribution to the signal of Exam-ple 6.1. Use the analytic signal and provide plots similar to those of ExamExam-ple 6.1.
% Example 6.3 and Figures 6.7 and 6.8
% Example of the use of the Wigner-Ville distribution
% Applies the Wigner-Ville to data similar to that of Example
% 6.1, except that the data has been shortened from 1024 to 512
% to improve run time.
%
clear all; close all;
% Set up constants (same as Example 6–1) fs = 500; % Sample frequency
N = 512; % Signal length
f1 = 10; % First frequency in Hz f2 = 40; % Second frequency in Hz
FIGURE6.7 Wigner-Ville distribution for the two sequential sinusoids shown in Figure 6.3. Note that while both the frequency ranges are better defined than in Figure 6.2 produced by the STFT, there are large cross products generated in the region between the two actual signals (central peak). In addition, the distribu-tions are sloped inward along the time axis so that onset time is not as precisely defined as the frequency range.
TLFeBOOK
FIGURE6.8 Contour plot of the Wigner-Ville distribution of two sequential sinu-soids. The large cross products are clearly seen in the region between the actual signal energy. Again, the slope of the distributions in the time domain make it difficult to identify onset times.
%
% Construct a step change in frequency as in Ex. 6–1 tn = (1:N/4)/fs;
x = [zeros(N/4,1); sin(2*pi*f1*tn)’; sin(2*pi*f2*tn)’;
zeros(N/4,1)];
%
% Wigner-Ville analysis
x = hilbert(x); % Construct analytic function [WD,f,t] = wvd(x,fs); % Wigner-Ville transformation WD = abs(WD); % Take magnitude
mesh(t,f,WD); % Plot distribution view(100,40); % Use different view ....Labels and axis....
figure
contour(t,f,WD); % Plot as contour plot ....Labels and axis....
The functionwwdcomputes the Wigner-Ville distribution.
function [WD,f,t] = wvd(x,fs)
% Function to compute Wigner-Ville time–frequency distribution
% Outputs
% WD Wigner-Ville distribution
% f Frequency vector for plotting
% t Time vector for plotting
TLFeBOOK
Time–Frequency Analysis 165
if N< xcol % Make signal a column vector if necessary x = x!; % Standard (non-complex) transpose N = xcol;
end
WD = zeros(N,N); % Initialize output
t = (1:N)/fs; % Calculate time and frequency vectors f = (1:N)*fs/(2*N);
%
%
%Compute instantaneous autocorrelation: Eq. (7) for ti = 1:N % Increment over time
taumax = min([ti-1,N-ti,round(N/2)-1]);
tau = -taumax:taumax;
% Autocorrelation: tau is in columns and time is in rows WD(tau-tau(1)ⴙ1,ti) = x(tiⴙtau) .* conj(x(ti-tau));
end
%
WD = fft(WD);
The last section of code is used to compute the instantaneous autocorrela-tion funcautocorrela-tion and its Fourier transform as in Eq. (9c). The forloop is used to construct an array,WD, containing the instantaneous autocorrelation where each column contains the correlations at various lags for a given time, ti. Each column is computed over a range of lags,± taumax. The first statement in the loop restricts the range of taumaxto be within signal array: it uses all the data that is symmetrically available on either side of the time variable,ti. Note that the phase of the lag signal placed in array WD varies by column (i.e., time).
Normally this will not matter since the Fourier transform will be taken over each set of lags (i.e., each column) and only the magnitude will be used. How-ever, the phase was properly adjusted before plotting the instantaneous autocor-relation in Figure 6.1. After the instantaneous autocorautocor-relation is constructed, the Fourier transform is taken over each set of lags. Note that if an array is presented to the MATLAB fftroutine, it calculates the Fourier transform for each col-umn; hence, the Fourier transform is computed for each value in time producing a two-dimensional function of time and frequency.
The Wigner-Ville is particularly effective at detecting single sinusoids that change in frequency with time, such as the chirp signal shown in Figure 6.5 and used in Example 6.2. For such signals, the Wigner-Ville distribution produces very few cross products, as shown in Example 6.4.
TLFeBOOK
Example 6.4 Apply the Wigner-Ville distribution to a chirp signal the ranges linearly between 20 and 200 Hz over a 1 second time period. In this example, use the MATLABchirproutine.
% Example 6.4 and Figure 6.9
% Example of the use of the Wigner-Ville distribution applied to
% a chirp
% Generates the chirp signal using the MATLAB chirp routine
%
clear all; close all;
% Set up constants % Same as Example 6.2 fs = 500; % Sample frequency
N = 512; % Signal length
f1 = 20; % Starting frequency in Hz f2 = 200; % Frequency after 1 second (end)
% in Hz
%
% Construct “chirp” signal tn = (1:N)/fs;
FIGURE6.9 Wigner-Ville of a chirp signal in which a single sine wave increases linearly with time. While both the time and frequency of the signal are well-defined, the amplitude, which should be constant, varies considerably.
TLFeBOOK
Time–Frequency Analysis 167
x = chirp(tn,f1,1,f2)’; % MATLAB routine
%
% Wigner-Ville analysis
x = hilbert(x); % Get analytic function [WD,f,t] = wvd(x,fs); % Wigner-Ville—see code above WD = abs(WD); % Take magnitude
mesh(t,f,WD); % Plot in 3-D ...3D labels, axis, view...
If the analytic signal is not used, then the Wigner-Ville generates consider-ably more cross products. A demonstration of the advantages of using the ana-lytic signal is given in Problem 2 at the end of the chapter.
Choi-Williams and Other Distributions
To implement other distributions in Cohen’s class, we will use the approach defined by Eq. (13). Following Eq. (13), the desired distribution can be obtained by convolving the related determining function (Eq. (17)) with the instantaneous autocorrelation function (Rx(t,τ); Eq. (7)) then taking the Fourier transform with respect to τ. As mentioned, this is simply a two-dimensional filtering of the instantaneous autocorrelation function by the appropriate filter (i.e., the deter-mining function), in this case an exponential filter. Calculation of the instanta-neous autocorrelation function has already been done as part of the Wigner-Ville calculation. To facilitate evaluation of the other distributions, we first extract the code for the instantaneous autocorrelation from the Wigner-Ville function,wvd in Example 6.3, and make it a separate function that can be used to determine the various distributions. This function has been termed int_autocorr, and takes the data as input and produces the instantaneous autocorrelation function as the output. These routines are available on the CD.
function Rx = int_autocorr(x)
% Function to compute the instantenous autocorrelation
% Output
Rx = zeros(N,N); % Initialize output
%
% Compute instantaneous autocorrelation for ti = 1:N % Increment over time
taumax = min([ti-1,N-ti,round(N/2)-1]);
tau = -taumax:taumax;
TLFeBOOK
Rx(tau-tau(1)ⴙ1,ti) = x(tiⴙtau) .* conj(x(ti-tau));
end
The various members of Cohen’s class of distributions can now be imple-mented by a general routine that starts with the instantaneous autocorrelation function, evaluates the appropriate determining function, filters the instantaneous autocorrelation function by the determining function using convolution, then takes the Fourier transform of the result. The routine described below, cohen, takes the data, sample interval, and an argument that specifies the type of distri-bution desired and produces the distridistri-bution as an output along with time and frequency vectors useful for plotting. The routine is set up to evaluate four different distributions: Choi-Williams, Born-Jorden-Cohen, Rihaczek-Marge-nau, with the Wigner-Ville distribution as the default. The function also plots the selected determining function.
function [CD,f,t] = cohen(x,fs,type)
% Function to compute several of Cohen’s class of time–frequencey
% distributions
%
% Outputs
% CD Desired distribution
% f Frequency vector for plotting
% t Time vector for plotting
%Inputs
% x Complex signal
% fs Sample frequency
% type of distribution. Valid arguements are:
% ’choi’ (Choi-Williams), ’BJC’ (Born-Jorden-Cohen);
% and ’R_M’ (Rihaczek-Margenau) Default is Wigner-Ville
%
% Assign constants and check input
sigma = 1; % Choi-Williams constant L = 30; % Size of determining function
%
[N, xcol] = size(x);
if N< xcol % Make signal a column vector if
x = x’; % necessary
N = xcol;
end
t = (1:N)/fs; % Calculate time and frequency f = (1:N) *(fs/(2*N)); % vectors for plotting
%
% Compute instantaneous autocorrelation: Eq. (7)
TLFeBOOK
Time–Frequency Analysis 169
CD = int_autocorr(x);
if type(1)== ’c’ % Get appropriate determining
% function
G = zeros(N,N); % Default Wigner-Ville G(N/2,N/2) = 1;
end
% figure
mesh(1:L-1,1:L-1,G); % Plot determining function xlabel(’N’); ylabel(’N’); % and label axis
zlabel(’G(,N,N)’);
%
% Convolve determining function with instantaneous
% autocorrelation
CD = conv2(CD,G); % 2-D convolution
CD = CD(1:N,1:N); % Truncate extra points produced
% by convolution
%
% Take FFT again, FFT taken with respect to columns CD = flipud(fft(CD)); % Output distribution
The code to produce the Choi-Williams determining function is a straight-forward implementation of G(t,τ) in Eq. (17) as shown below. The function is generated for only the first quadrant, then duplicated in the other quadrants. The function itself is plotted in Figure 6.10. The code for other determining functions follows the same general structure and can be found in the software accompany-ing this text.
function G = choi(sigma,N)
% Function to calculate the Choi-Williams distribution function
% (Eq. (17)
G(1,1) = 1; % Compute one quadrant then expand for j = 2:N/2
FIGURE6.10 The Choi-Williams determining function generated by the code below.
wt = wt—G(1,j); % Normalize array so that
% G(n,j) = 1 for i = 1:N/2
G(i,j) = G(i,j)/wt;
end end
%
% Expand to 4 quadrants
G = [ fliplr(G(:,2:end)) G]; % Add 2nd quadrant
G = [flipud(G(2:end,:)); G]; % Add 3rd and 4th quadrants To complete the package, Example 6.5 provides code that generates the data (either two sequential sinusoids or a chirp signal), asks for the desired distributions, evaluates the distribution using the functioncohen, then plots the result. Note that the code for implementing Cohen’s class of distributions is written for educational purposes only. It is not very efficient, since many of the operations involve multiplication by zero (for example, see Figure 6.10 and Figure 6.11), and these operations should be eliminated in more efficient code.
TLFeBOOK
Time–Frequency Analysis 171
FIGURE6.11 The determining function of the Rihaczek-Margenau distribution.
Example 6.5 Compare the Choi-Williams and Rihaczek-Margenau dis-tributions for both a double sinusoid and chirp stimulus. Plot the Rihaczek-Margenau determining function* and the results using 3-D type plots.
% Example 6.5 and various figures
% Example of the use of Cohen’s class distributions applied to
% both sequential sinusoids and a chirp signal
%
clear all; close all;
global G;
% Set up constants. (Same as in previous examples)
fs = 500; % Sample frequency
N = 256; % Signal length
f1 = 20; % First frequency in Hz
f2 = 100; % Second frequency in Hz
%
% Construct a step change in frequency
signal_type = input (’Signal type (1 = sines; 2 = chirp):’);
if signal_type== 1 tn = (1:N/4)/fs;
x = [zeros(N/4,1); sin(2*pi*f1*tn)’; sin(2*pi*f2*tn)’;
*Note the code for the Rihaczek-Margenau determining function and several other determining functions can be found on disk with the software associated with this chapter.
TLFeBOOK
zeros(N/4,1)];
x = hilbert(x); % Get analytic function [CD,f,t] = cohen(x,fs,type); % Cohen’s class of
% transformations
CD = abs(CD); % Take magnitude
% % Plot distribution in
figure; % 3-D
mesh(t,f,CD);
view([85,40]); % Change view for better
% display ...3D labels and scaling...
heading = [type ’ Distribution’]; % Construct appropriate eval([’title(’,’heading’, ’);’]); % title and add to plot
%
% figure;
contour(t,f,CD); % Plot distribution as a contour plot
xlabel(’Time (sec)’);
ylabel(’Frequency (Hz)’);
eval([’title(’,’heading’, ’);’]);
This program was used to generate Figures 6.11–6.15.
In this chapter we have explored only a few of the many possible time–
frequency distributions, and, necessarily, covered only the very basics of this extensive subject. Two of the more important topics that were not covered here are the estimation of instantaneous frequency from the time–frequency distribu-tion, and the effect of noise on these distributions. The latter is covered briefly in the problem set below.
PROBLEMS
1. Construct a chirp signal similar to that used in Example 6.2. Evaluate the analysis characteristics of the STFT using different window filters and sizes.
Specifically, use window sizes of 128, 64, and 32 points. Repeat this analysis
TLFeBOOK
FIGURE6.12 Choi-Williams distribution for the two sequential sinusoids shown in Figure 6.3. Comparing this distribution with the Wigner-Ville distribution of the same stimulus, Figure 6.7, note the decreased cross product terms.
FIGURE 6.13 The Rihaczek-Margenau distribution for the sequential sinusoid signal. Note the very low value of cross products.
173
TLFeBOOK
FIGURE6.14 The Choi-Williams distribution from the chirp signal. Compared to the Wigner-Ville distribution (Figure 6.9), this distribution has a flatter ridge, but neither the Choi-Williams nor the the Wigner-Ville distributions show significant cross products to this type of signal.
using a Chebyshev window. (Modifyspectogto apply the Chebyshev window, or else use MATLAB’sspecgram.) Assume a sample frequency of 500 Hz and a total time of one second.
2. Rerun the two examples that involve the Wigner-Ville distribution (Exam-ples 6.3 and 6.4), but use the real signal instead of the analytic signal. Plot the results as both 3-D mesh plots and contour plots.
3. Construct a signal consisting of two components: a continuous sine wave of 20 Hz and a chirp signal that varies from 20 Hz to 100 Hz over a 0.5 sec time period. Analyze this signal using two different distributions: Wigner-Ville and Choi-Williams. Assume a sample frequency of 500 Hz, and use analytical signal.
4. Repeat Problem 3 above using the Born-Jordan-Cohen and Rihaczek-Margenau distributions.
5. Construct a signal consisting of two sine waves of 20 and 100 Hz. Add to
5. Construct a signal consisting of two sine waves of 20 and 100 Hz. Add to