We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 21
Chapter 1
Essentials of Signal Processing
Abstract This chapter introduces some of the basic signal processing concepts that will be used throughout
this book. The goal is to enable the reader to appreciate the concepts and apply them in building a basic
communication system. Concepts covered include - signal generation techniques for generating well known
test signals like rectangular pulse, sine wave, square wave, chirp signal and gaussian pulse, interpreting FFT
results and extracting magnitude/phase information using FFT, computation of power and energy of a signal,
various methods to compute convolution of two signals, analytic signal and applications, FIR/IIR filters.
1.1 Generating standard test signals
In experimental modeling and simulation, simple test inputs such as sinusoidal, rectangular pulse, gaussian
pulse, and chirp signals are widely used. These test signals act as stimuli for the simulation model and the
response of the model to the stimuli is of great interest in design verification,
1.1.1 Sinusoidal signals
In order to generate a sine wave, the first step is to fix the frequency f of the sine wave. For example, we wish
to generate a f= 10Hz sine wave whose minimum and maximum amplitudes are —1V and +1V respectively.
Given the frequency of the sinewave, the next step is to determine the sampling rat.
For baseband signals, the sampling is straight forward. By Nyquist Shannon sampling theorem, for faithful
reproduction of a continuous signal in discrete domain, one has to sample the signal at a rate f, higher than
at-least twice the maximum frequency fm contained in the signal (actually, itis twice the one-sided bandwidth
‘occupied by a real signal. For a baseband signal bandwidth (0 to f,) and maximum frequency fm in a given
band are equivalent).
Matlab is a software that processes everything in digital, In order to obtain a smooth sine wave, the sam-
pling rate must be far higher than the prescribed minimum required sampling rate which is at least twice the
frequency f - as per Nyquist-Shannon theorem, Hence we need to sample the input signal at a rate signifi-
cantly higher than what the Nyquist criterion dictates. Higher oversampling rate requires more memory for
signal storage. It is advisable to keep the oversampling factor to an acceptable value.
‘An oversampling factor of 30 is chosen in the following code snippet. This is to plot a smooth continuous-
like sine wave. Thus the sampling rate becomes f, = 30x f = 30 x 10= 300#fz. Ifa phase shift is desired for
the sine wave, specify it too. The resulting plot from the code snippet shown next, is given in Figure 1.14 1 Bssentials of Signal Processing
Program 1.1: sinusoidal signal.m: Simulate a sinusoidal signal with given sampling rate
#510; %frequency of sine wave
overSampRate=30; Xoversampling rate
fstoverSampRatesf; sampling frequency
phase = 1/34pi; %desired phase shift in radians
Acyl = 5; %to generate five cycles of sine wave
t=0:1/Fs:nCyl*l/f-1/Fs; %time base
g=sin(2*piefettphase
plot(t,g); title({'Sine Wave
replace with cos if a cosine wave is desired
+ nun2str(f), *H2"1);
Sine wave f=10 Hz,
0 o1 02 03 04 05
Time (s)
Fig. 1.1: A 10Hz sinusoidal wave with 5 cycles and phase shift 1/37 radians
11.2 Square wave
‘The most logical way of transmitting information across a communication channel is through a stream of
square pulse ~ a distinct pulse for ‘0° and another for ‘I’. Digital signals are graphically represented as square
waves with certain symbol/bit period. Square waves are also used universally in switching circuits, as clock
signals synchronizing various blocks of digital circuits, as reference clock for a given system domain and so
on
Square wave manifests itself as a wide range of harmonics in frequency domain and therefore can cause
electromagnetic interference, Square waves ate periodic and contain odd harmonics when expanded as Fourier
Series (where as signals like saw-tooth and other real word signals contain harmonics at all integer frequen-
cies). Since a square wave literally expands to infinite number of odd harmonic terms in frequency domain,
approximation of square wave is another area of interest. The number of terms of its Fourier Series expansion,
taken for approximating the square wave is often seen as Gibbs phenomenon, which manifests as ringing effect
at the comers of the square wave in time domain,1.1 Generating standard test signals
5
‘True square waves are a special class of rectangular waves with 50% duty cycle. Varying the duty cycle
of a rectangular wave leads to pulse width modulation, where the information is conveyed by changing the
duty-cycle of each transmitted rectangular wave. A true square wave can be simply generated by applying
ssignum function over a periodic function.
a(t) = sn [sinQ2a f)]
where f is the desired frequency of the square wave and the signum function is defined as
1 ifxo
Program 1.2: square.wave.m: Generate a square wave with given sampling rate
aay
(1.2)
F510; Bfrequency of sine wave in liz
overSanpRate=30; oversampling rate
FseoverSampRate*f; Xsampling frequency
ncyl = 5; Xto generate five cycles of square wave
£20: 1/fs:nCylal/f-1/Fs; tine base
& = sign(sin(2*pixfet));
» |plot(t,g); title(E’square Wave f=", numastr(f), 'H2"1);
Square wave f-10 Hz
1
05
3
a 0
E
0.5
A
0 of 02 08 04 08
Time (3)
Fig. 1.2: A 10Hz square wave with 5 cycles and 50% duty cycle
1.1.3 Rectangular pulse
An isolated rectangular pulse of amplitude A and duration T is represented mathematically as6 1 ssemalof Signal Processing
‘
alt) =A rect (4) as
where,
rect(t) = a4)
The following code simulates a rectangular pulse with desired pulse width and the resulting plot is shown,
in Figure 1.3.
Program 1.3: rectangular pulse.m: Generating a rectangular pulse with desired pulse width.
5500; “sampling frequency
T=0.2; Xwidth of the rectangule pulse in seconds
t2-0.5:1/Fs:0.5; %time base
ge(t >-T/2) .* (teT/2) + 0.5x(t==T/2) + 0.541 12);
Xgerectpuls(t,T); using inbuilt function (signal proc toolbox)
plot(t,g);title({' Rectangular Pulse width=", numastr(T),'s']);
Rectangular pulse width = 0.2s
ee
& &
Amplitude
°
S
05 0 05
Time(s)
Fig. 1.3: A rectangular pulse having pulse-width 0.25
114 Gaussian pulse
In digital communications, Gaussian Filters are employed in Gaussian Minimum Shift Keying - GMSK [1]
and Gaussian Frequency Shift Keying (GFSK), Two dimensional Gaussian filters are used in image processing
for producing Gaussian blurs. The impulse response of a Gaussian filter is Gaussian. Gaussian filters give no
overshoot with minimal rise and fall time when excited with a step function. Gaussian filter has minimum
group delay. The impulse response of a Gaussian filter is written as a Gaussian function1.1 Generating standard test signals 7
1
~ Vine’
8) as)
The following code generates a Gaussian pulse with 6 = 0.1. The resulting plot is given in Figure 1.4
Program 1.4: gaussian pulse.m: Generating a Gaussian pulse with desired pulse width
fs=80; Xsampling frequency
sigma=0.1;%standard deviation
0.5:1/F5:0.5; time base
g=1/ (sqrt (2api)*sigma)*(exp(-t. “2/(2¥sigma*2)));
s |plot(t,g); title({'Gaussian Pulse \sigma=', num2str(sigma),'s'J);
Gaussian pulse o=0.1 s
oO 05
Time(s)
Fig, 1.4; A Gaussian pulse with 6 = 0.15
LS Chirp signal
All the signals, discussed so far, do not change in frequency over time, Obtaining a signal with time-varying
frequency is of main focus here. A signal that varies in frequency over time is called chirp. The frequency of
the chirp signal can vary from low to high frequency (up-chirp) or from high to low frequency (low-chirp).
Chirp signals are encountered in many applications ranging from radar, sonar, spread spectrum, optical
communication, image processing, doppler effect, motion of a pendulum, as gravitation waves, manifestation
a frequency modulation (FM), echo location etc.
A linear chirp signal sweeps the frequency from low to high frequency (or vice-versa) linearly. One ap.
proach to generate a chirp signal is to concatenate a series of segments of sine waves each with increasing (or
decreasing) frequency in order. This method introduces discontinuities in the chirp signal due to the mismatch
in the phases of each such segments. Modifying the equation of a sinusoid to generate a chirp signal isa better
approach,
The equation for generating a cosine signal with amplitude A, angular frequency @ and initial phase ¢ is8 1 Essentials of Signal Processing
ale
A cos(ont +6) a6)
‘This can be writen as a function of instantaneous phase
x(0) =A cos(0(0) an
where 0(1) = apt + ¢ is the instantaneous phase of the sinusoid and itis linear in time. The time derivative of
instantaneous phase @(), is equal to the angular frequency a of the sinusoid.
4
fog 18)
FO) =o (8)
Instead of having the phase linear in time, let's change the phase to quadratic form and thus render it non-linear.
For some constant c,
6 (0) = 2a? + 2m for +6 (9)
‘Therefore, the equation for chirp signal takes the following form,
x(0) =A.cos (0(0)) =A cos (2mar? +2nfo1 +6) (1.10)
‘The frst derivative ofthe phase is the instantaneous angular frequency as given by
oy) = L010) = Aras +2mf0 aan
‘Hence, the time-varying frequency in Hz is given by
Silt) = 2at+ fo (1.12)
In the above equation, the frequency is no longer a constant, rather it is of time-varying nature with initial
frequency given by fy. Thus, from the above equation, given a time duration 7, the rate of change of frequency
is given by
fi-fo
a= Fe (1.13)
where, fo is the starting frequency of the sweep, fi is the frequency at the end of the duration T. Substituting
equations 1.12 and 1.13 in 1.11,
a = Loy = 20+.) (14)
From equations 1.11 and 1.13
a(t) = fear
2
=2n fla + fo)dr=20 K+ fot) +
=23 ce = 23 k 1.15)
=x (i+ fr) += = (5+ so) +6 as)
where, dy is a constant which will act as th inital phase of the sweep. Thus the modified equation for gener-
ating a chirp signal (from equations 1.10 and 1.15) is given by
x(t) =A cos (0(t)) =A cos [2f(1) + Go] (1.16)1.2. Interpreting FFT results - complex DFT, frequency bins and FFTShift 9
where, the time-varying frequency function is given by
JO=$t+h (17)
A chirp signal can be generated without using the inbuilt chirp function in Matlab's signal processing
toolbox. This is done by implementing a function that utilizes equations 1.12, 1.16 and 1.17. The implemented
function is shown next.
The implemented function accepts five arguments to generate a chinp signal: t - the discrete time base for
generating the chitp, fo - the initial frequency of the sweep, fy - the frequency at time fy and gy - the initial
phase of the chirp which is an optional argument. Ifthe initial phase is not supplied to the function, it assumes
the initial phase to be zero,
Program 1.5: chirp-signal.m: Function to generate a Chirp signal
1 [function gchirp_signal(t,#@,t1, #1, phase)
2 |g = chirp_signal(t,f0,t1,f1) generates samples of a linearly
2 |Xswept-frequency signal at the time instances defined in timebase
+ |%array t. The instantaneous frequency at time @ is f0 Hertz,
s |%The instantaneous frequency f1 is achieved at time t1. The argument
« |X'phase' is optional. It defines the initial phase of the signal
defined in radians, By default phase=0 radian
+ [if nargin==4, phase=0; end
» |ta=tc1); T=t1-t0; kecFI-fay/T;
0 |g-cos(2apix(k/2at+Fe) .xt=phase);
end
The following test script utilizes the above function and generates a chirp with starting frequency fo = 1Hz
at the start of the time base and f; = 2SHz at f, = 1s which is the end of the time base. From the PSD plot, it
ccan be ascertained that the signal energy is concentrated only upto 25Hz. The resulting plot is shown in Figure
15.
Program 1.6: chirp.test.m: Generating and plotting a chirp signal
1 [fs=500; xsampling frequency
2 |t=0:1/fs:1; Ktime base - upto 1 second
F0=1;% starting frequency of the chirp
Fi=fs/20; ‘frequency of the chirp at ti=1 second
s |g = chirp_signal(t,0,1,#1);
« |plot(t,g); title(Chirp Signal’);
1.2 Interpreting FFT results - complex DFT, frequency bins and FFTShift
Often, one is confronted with the problem of converting a time domain signal to frequency domain and vice.
versa. Fourier transform is an excellent tool to achieve this conversion and is ubiquitously used in many
applications. In signal processing, a time domain signal can be continuous or discrete and it can be aperiodic
or periodic. This gives rise to four types of Fourier transforms as listed in Table 1.1
From Table 1.1, we note that when the signal is discrete in one domain, it will be periodic in other domain.
Similarly, if the signal is continuous in one domain, it will be aperiodic (non-periodic) in another domain.1 Essentials of Signal Processing
Chirp Signal
0.2 0.4 0.6 08 1
Time(s)
Fig. 1.5: A finite record of a chirp signal
Table 1.1: Four types of Fourier transforms
“Transform ‘Nature of ime domain signal Nature of frequency spectrum
Fourier Transform (FT), (aka Continuous Time continuous, non-periodie ‘non-periodie,continuons
Fourier Transform (CTFT)
Discretestime Fourier Transform (DTFT) Liserete, non: periodic periodie,continuous
Fourier Series (FS) continuous, periodic non-periodic, discrete
Discrete Fourier Transform (DFT) discrete, periodic periodic discrete
For simplicity, lets not venture into the specific equations for each of the transforms above, We will limit
our discussion to DFT, that is widely available as part of software packages like Matlab, SciPy(python) etc..,
however we can approximate other transforms using DFT.
1.2.1 Real and complex DFT
For each of the listed transforms above, there exist areal version and complex version. The real version of the
transform, takes in a real numbers and gives two sets of real frequency domain points - one set representing
coefficients over cosine basis function and the other set representing the coefficient over sine basis function
‘The complex version of the transforms represent positive and negative frequencies in a single array. The
complex versions are flexible, that it can process both complex valued signals and real valued signals. Figure
1.6 captures the difference between real DFT and complex DFT.
1.2.1.1 Real DFT
Consider the case of N-point real DFT. It takes in N samples of real-valued time domain waveform xjn] and
gives two arrays of length NV /2 +1, each set projected on cosine and sine functions respectively.1.2. Interpreting FFT results - complex DFT, frequency bins and FFTShift n
2S mn
Keil = 2 Y sos (= )
«gy
Here, the time domain index n runs from 0 —+ N, the frequency domain index k runs from 0 -> N/2. The
real-valued time domain signal x(n] can be synthesized from the real DFT pairs as
xin] -¥x. Kjos (25) = XinlK]sin (#) (9)
a
Caveat: When using the synthesis equation, the values X-[0] and X;e[N/2} must be divided by two. This
problem is due to the fact that we restrict the analysis to real-values only. These type of problems can be
avoided by using complex version of DFT.
‘Time domain | Frequency domain
x(n] real valued Real DET
| X,elle|~ real valued
D Ma 5 wa (cosine terms)
Kink) ~r0al valued
(sine terms)
| ° Ne2 .
Complex DFT
xfn] - complex valued | X(k] - complex valued
3 wt NR NA
+tve frequencies |
. ve frequencies
DC frequency component
/2
is common to positive and negative frequencies
Nyquist frequency component at
Fig. 1.6: Real and complex DFT
1.2.1.2 Complex DFT
Consider the case of N-point complex DFT. It takes in N samples of complex-valued time domain waveform
-x{n] and produces an array Xk] of length N.2 1 Essentials of Signal Processing
TAC ant /w
Xi =< Y alle Pre 1.20)
May xt (1.20)
‘The arrays values are interpreted as follows
+ X/0] represents DC frequency component
+ Next V/2 terms are positive frequency components with X(N/2| being the Nyquist frequency (which is
equal to half of sampling frequency)
+ Next NV/2—1 terms are negative frequency components (note: negative frequency components are the
phasors rotating in opposite direction, they can be optionally omitted depending on the application)
The corresponding synthesis equation (reconstruct x{n] from frequency domain samples XK) is,
xin] = Yo X[keenl8 (21)
&
From equation 1.18, we can see that the real DFT is computed by projecting the signal on cosine and sine
basis functions. However, the complex DFT, in equation!.20, projects the input signal on exponential basis
functions (Euler's formula - e® = cos6 + isin® connects these two concepts)
‘When the input signal in the time domain is real valued, the complex DFT zero-fills the imaginary part
during computation (That's its flexibility and avoids the caveat needed for real DFT). Figure 1.7 shows how to
interpret the raw FFT results in Matlab that computes complex DFT. The specifics will be discussed next with
an example.
X[K] - complex valued
N-1_ FFT equation indices
Ll
O Af 2af (N/2jaf (N-1)Af frequency bins
10203) N/2#1 —N- +—Matlab array indices,
Fig. 1.7: Interpretation of frequencies in complex DFT output
1.2.2 Fast Fourier Transform (FFT)
‘The FFT, implemented in Scipy.fipack package, is an algorithm published in 1965 by J.W.Cooley and
J.W-Tuckey for efficiently calculating the DFT (2. In its simplest implementation, parallel DFT computa-
tions are performed on the odd, even indexed samples of a record and the results are combined, If the number1.2. Interpreting FFT results - complex DFT, frequency bins and FFTShift B
of samples taken for the computation is an integer power of 2, the DFT computation can be recursively per-
formed, there by offering significant reductions in the computation time. This is called radix — 2 FET. The
FFT length can also be odd as used in a particular FFT implementation called Prime-factor FFT algorithm [3]
[4), where the FFT length factors into two co-primes.
FFT is widely available in software packages like Matlab, Scipy etc... FFT in Matlab/Scipy implements the
complex version of DFT. Matlab’s FFT implementation computes the complex DFT that is very similar to the
above equations, except for the scaling factor. For comparison, the Matlab’s FFT implementation computes
the complex DFT and its inverse as
Net ,
XI) = Yale Pe
=
1M
=y LXer (1.22
=
‘The Matlab commands that implement the above equations are FFT and IFFT respectively. The correspond-
ing syntax is as follows
X= FFt(K,N) Xcompute XIK]
x = UfFEOXN) Xeompute xLn]
1.2.3 Interpreting the FFT results
Let’s assume that the x(n] is a time domain cosine signal of frequency fe = 10 Hz. For representing it in the
computer memory, the signal is sampled at a frequency f, = 32+ fc (Figure 1.8)
Program 1,7: Generating a 2 seconds record of 10 Hz. cosine wave
1 [Feete;xfrequency of the carrier
fs=32sfc;%sampling frequency with oversampling factor=32
H1/F8:2-1/¥8;82 seconds duration
x=cos(2apiafert) ;%time domain signal (real nunber)
subplot(3,1,1); plot(t,x);hold on; %plot the signal
title('x(nl=cos(2 \pi 10 )'); xlabel('t=nT_s'); ylabel(’xCn]');
Let’s apply a N = 2° = 256 point FFT on the discrete-time signal x{n
Program 1.8: Taking N-point DFT
N=256; MFFT size
X = FFt(x,N);2N-point complex DFT, output contains DC at index 1
» |RNyquist frequency at N/2+1 th index positive frequencies from
+ |index 2 to N/2 negative frequencies from index N/2+1 to N
Note: The FFT length should be sufficient to cover the entire length of the input signal. If Nis less than the
length of the input signal, the input signal will be truncated when computing the FFT. The cosine wave x(n] is
of 2 seconds duration and it will have 640 points (a 10/1z frequency wave sampled at 32 times oversampling
factor will have 2 x 32 x 10 = 640 samples in 2 seconds of the record). Since the input signal x(n] is periodic,
we can safely use N = 256 point FFT, anyways the FFT will extend the signal when computing the F
Due to Matlab’s index starting at 1, the DC component of the FFT decomposition is present at index 1“4 1 Bssetials of Signal Processing
x[n]=cos(2 7 10)
0 05 1 15 2
t=nT.
Fig. 1.8: A 2 seconds record of 10 Hz cosine wave
Dex)
1.1762e-14 (approximately equal to zero)
Note that the index for the raw FFT are integers from I > N. We need to process it to convert these integers.
to frequencies. That is where the sampling frequency counts. Each point/bin in the FFT output array is spaced
by the frequency resolution A f, that is calculated as
f
a 23)
af=# (1.23)
‘where, f; is the sampling frequency and NV is the FFT size that is considered. Thus, for our example, each point
in the array is spaced by the frequency resolution
_ kB 320
AI= N= 356 = 356
25Hz (1.24)
‘The 10H1z cosine signal will register a spike at the 8th sample (10/1.25=8) - located at index 9 in Figure 1.9.
>> abs(X(8:10)) Xdisplay samples 7 to 9
ans = 0.0000 128.0000 0.0000
‘Therefore, using the frequency resolution, the entire frequency axis can be computed as
Program 1.9: Computing the frequency axis for plotting
Xealculate frequency bins with FFT
GF=FS/N Frequency resolution
sampleIndex = @:N-1; iran index for FFT plot
FesampleIndextdf; x-axis index converted to frequencies
Now, plot the absolute value of the FFT against frequencies - the resulting plot is shown in the Figure 1.9.
Program 1.10: Plotting the frequency domain view of a signal
‘subplot (3,1,2); stem(sanpleIndex,abs(X)); %sample values on x-axis
title( X[k]'); xlabel('k'); ylabel(' |X(K) |");
subplot (3,1,3); stem(f,abs(X)); %x-axis represent frequencies
title( X[f]'); xlabel(' frequencies (f)'); ylabel('|X(F)I')1.2. Interpreting FFT results - complex DFT, frequency bins and FFTShift 1s
fier the frequency axis is properly transformed with respect to the sampling frequency, we note that the
cosine signal has registered a spike at 10#z. In addition to that, it has also registered a spike at 256-8 =
248"* sample that belongs to the negative frequency portion. Since we know the nature of the signal, we can
optionally ignore the negative frequencies. The sample at the Nyquist frequency (J,/2) mark the boundary
between the positive and negative frequencies.
>> nyquistIndex=N/2+1;
>> X(nyquistIndex-2:nyquistIndex+2).'
ans =
1.00-13 *
-0.2428 + 0.04041
0.1897 + 0.09991
-0.3784
-0.1897 - 0.09991
-0,2428 - 0.04041
Note that the complex numbers surrounding the Nyquist index are complex conjugates and are present at
positive and negative frequencies respectively.
° 50 0 150200250
os. 100 180200250300
frequencies ()
Fig. 1.9: FFT magnitude response plotted against - sample index (top) and computed frequencies (bottom)
1.2.4 FFTShift
From Figure 1.9, we see that the frequency axis starts with DC, followed by positive frequency terms which
is in turn followed by the negative frequency terms. To introduce proper order in the x-axis, one can use
FFTshift function Matlab, which arranges the frequencies in order: negative frequencies -> DC - positive
frequencies. The fftshift function need to be carefully used when N is odd.
For even N, the original order returned by FFT is as follows (note: here, all indices correspond to Matlab’s
indices)16 1 Bssentials of Signal Processing
+ X{I] represents DC frequency component
+ X/2] to X(N/2] terms are positive frequency components
+ X/N/2+1) is the Nyquist frequency (F,/2) that is common to both positive and negative frequencies. We
will consider it as part of negative frequencies to have the same equivalence with the ffishift function
+ X|N/2+1] to X(N] terms are considered as negative frequency components
FFTshift shifts the DC component tothe center of the spectrum. It is important to remember that the Nyquist
frequency at the (N/2+1)th Matlab index is common to both positive and negative frequency sides. FFTshift
‘command puts the Nyquist frequency in the negative frequency side. This is captured in the Figure 1.10.
X[k] - complex valued FET shift X[k] - complex valued
G 4 —* LETT TT)
Nz 1 (__,—Jpet___J
be wt ~ve frequencies tye frequencies
+ve frequencies
-ve frequencies
FETshift
—>
0 Af 2af--(N/2jaf~ (N= 1)Af — (N/2)AF
12 3 N/2+1 N Die N/241 ON
Matlab array index
Fig. 1.10: Role of FFTShift in ordering the frequencies (assumption: N is even)
‘Therefore, when N is even, ordered frequency axis is set as
=afxi-Zxi, wherei=[-X,.- *
paaprictent, whet [Bon toon’ 25
‘When WV is odd, the ordered frequency axis should be set as
=afxi-%xi, wherei- |S... Net
SaAfxi=Zxi, where | Foe hObe S 1] (1.26)
‘The following code snippet, computes the fftshift using both the manual method and using the Matlab’s
in-built command. The results are plotted by superimposing them on each other. The plot in Figure I.1 shows
that both the manual method and fftshift method are in good agreement. Comparing the bottom figures in the
Figure 1.9 and Figure 1.11, we see that the ordered frequency axis is more meaningful to interpret.
Program 1.11: Plotting magnitude response using FFTShift
Xtwo-sided FFT with negative frequencies on left and positive
xfrequencies on right. Following works only if N is even
Xfor odd N see equation above
X1 = COX(N/2#1:N)) X(1:N/2)]; Korder frequencies without using FFtShift1.2. Interpreting FFT results - complex DFT, frequency bins and FFTShift 1”
s [x2 = fftshift(X);%order frequencies by using fftshift
df=FS/N; %frequency resolution
sampleIndex = -N/2:N/2-1; %raw index for FFT plot
Fesamplelndextdf; x-axis index converted to frequencies
Xplot ordered spectrum using the two methods
Figure; subplot(2, 1,1) ;stem(sampleIndex, abs(X1)) ;hold on;
stem(sampleIndex, abs(X2),'r') sample index on x-axis
title('Frequency Domain’); xlabel('k'); ylabel¢'|X(k)|');
subplot(2,1,2);stem(F,abs(X1)); stem(F,abs(X2), 'r')
xlabel('frequencies (f)'); ylabel(' |X(F)|');%frequencies on x-axis
|X)
00 50 ° 50 "00
f)
1x
“0100-50 0S 100 SD
Frequencies ()
Fig. 1.1: Magnitude response of FFT result after applying FFTShift : plotted against sample index (top) and
against computed frequencies (bottom)
1.2.5 IFFTShift
‘One can undo the effect of Fftshift by employing ifftshift function. The ifftshift function restores
the raw frequency order. If the FFT output is ordered using fftshift function, then one must restore the fre-
quency components back to original order before taking IFFT - the Inverse Fast Fourier Transform, Following
statements are equivalent.
X = FFEOK,N) Kcompute XEK]
x = UfFEOKN) Keompute xLn]
X = FPtshift(FFt(x,N)); Stake FFT and rearrange frequency order18 1 Essentials of Signal Processing
x = ifft(ifftshift(X,N)% restore raw freq order and then take IFFT
1.2.6 Some observations on FFTShift and IF FTShift
When N is odd and for an arbitrary sequence, the Fftshift and ifftshift functions will produce different
results, However, when they are used in tandem, it restores the original sequence.
>> x=[0,1,2,3,4,5,6,7,8]
0 1 2 3 4 5 6 7 8
>> fftshiftOo
5 6 7 8 6 1 2 3 4
>>. ifftshiftGo
4.05 6 7 8 8 1 2 3
>>. ifftshift(Frtshift(x))
® 1 2 3 4 5 6 7 8
>>. fftshift(ifftshift(o)
® 1 2 3 4 5 6 7 8B
When Wis even and for an arbitrary sequence, the FFtshift and iff tshift functions will produce the same
result, When they are used in tandem, it restores the original sequence.
>> x=[0,1,2,3,4,5,6,7]
eo 1 2 3 4 5 6 7
>> fftshift(x)
4.5 6 7T 8 1 2 3
>> ifftshift(x)
4°55 6 7 @ 1 2 3
>> ifftshift(fftshift Go)
o 1 2 3 4 8 6 7
o> fftshift(ifftshiftGo)
o 1 2 3 4 8 6 7
1.3 Obtaining magnitude and phase information from FFT.
For the discussion here, lets take an arbitrary cosine function of the form x(t) = Acos (27 fut +) and proceed
step by step as follows
+ Represent the signal x(t) in computer (discrete-time x[n)) and plot the signal (time domain)
+ Represent the signal in frequency domain using FFT (X (k))
+ Extract magnitude and phase information from the FFT result
+ Reconstruct the time domain signal from the frequency domain samples
1.3.1 Discrete-time domain representation
Consider a cosine signal of amplitude A = 0.5, frequency fe = 10Hz and phase 9 = 1/6 radians (or 30° )1.3. Objaining magnitude and phase information from FFT 19
x(t) =0.5 cos (2101 + 2/6) (1.27)
In order to represent the continuous time signal x(*) in computer memory (Figure 1.12), we need to sample the
signal at sufliciently high rate (according to Nyquist sampling theorem). I have chosen a oversampling factor
‘of 32 so that the sampling frequency will be f, = 32 x fc, and that gives 640 samples in a 2 seconds duration
of the waveform record.
Program 1.12: Representing and storing a signal in computer memory
A= 0,5; Hamplitude of the cosine wave
Fc=10;%frequency of the cosine wave
phase=30; desired phase shift of the cosine in degrees
Fs=32xfc;Xsampling frequency with oversampling factor 32
t20:1/fs:2-1/f5;%2 seconds duration
phi = phasexpi/180; convert phase shift in degrees in radians
x=Atcos(2apisfcatephi) ;%time domain signal with phase shift
» |Figure; plot(t,x); xplot the signal
x(t) = 0.5 cos (2710t + 7/6}
08 (t) (2x 10t + 7/6)
go
05
0 0s 1 18 2
time (t seconds)
Fig. 1.12: Finite record of a cosine signal
1.3.2 Representing the signal in frequency domain using FFT
Let's represent the signal in frequency domain using the FFT function. The FFT function computes N-point
complex DFT. The length of the transformation N should cover the signal of interest, otherwise we will
loose some valuable information in the conversion process to frequency domain. However, we can choose a
reasonable length if we know about the nature of the signal. For example, the cosine signal of our interest is
periodic in nature and is of length 640 samples (for 2 seconds duration signal). We can simply use a lower
number N = 256 for computing the FFT. In this case, only the first 256 time domain samples will be considered
for taking FFT. However, we do not need to worry about loss of any valuable information, as the 256 samples
will have sufficient number of cycles to extract the frequency of the signal
Program 1.13: Represent the signal in frequency domain using FET
i=256; “FFT size
2 |X = 1/NeFFtshift(FFtCC,N));2N-point complex DFT20 1 Essentials of Signal Processing
In the code above, ff tshift is used only for obtaining a nice double-sided frequency spectrum that delin-
ceates negative frequencies and positive frequencies in order. This transformation is not necessary. A scaling
factor 1/N was used to account for the difference between the FFT implementation in Matlab and the text
definition of complex DFT as given in equation 1.20.
1.3.2.1 Extract magnitude of frequency components (magnitude spectrum)
‘The FFT function computes the complex DFT and hence results in a sequence of complex numbers of form
Xre-+ iXim. The magnitude spectrum is computed as
(x(k) = XB +83, (1.28)
For oblaining a double-sided plot, the ordered frequency axis, obtained using fFtshift, is computed based
‘on the sampling frequency and the magnitude spectrum is plotted (Figure 1.13).
Program 1.14: Extract magnitude information from the FFT result
df=fS/N; efrequency resolution
sampleIndex = -N/2:N/2-1; “ordered index for FFT plot
fesamplelndexadf; %x-axis index converted to ordered frequencies
stem(f,abs(X)); %nagnitudes vs frequencies
xlabel('f (H2)'); ylabel(’|X(k) |");
Magnitude spectrum
0.28
IX(k)|
0.05 f (Hz)
“30 -20 “10 ° 10 20 30
Fig. 1.13: Extracted magnitude information from the FFT result
1.3.2.2. Extract phase of frequency components (phase spectrum)
Extracting the correct phase spectrum is a tricky business. I will show you why it is so. The phase of the
spectral components are computed as
sm (8) w1.3. Objaining magnitude and phase information from FFT a
ran function will prove disastrous unless additional precautions are taken. The atan function computes the
inverse tangent over two quadrants only, i. it will return values only in the [—7/2, 7/2) interval. Therefore,
the phase need to be unwrapped properly. We can simply fix this issue by computing the inverse tangent over
all the four quadrants using the atan2(Xing,Xre) function. Let’s compute and plot the phase information using
‘atan2 function and see how the phase spectrum looks.
Program 1.15: Extracting phase information from the FFT result using atan? function
1 [phase=atan2(imag(X) ,real (X))#180/pi; phase information
» |plot(F phase); %ohase vs frequencies
200 Phase spectrum
100
Xo
N
100
(Hz)
-200
150 -100=SO5D 50 100 «180
Fig. 1.14: Extracted phase information from the FFT result - phase spectrum is noisy
‘The phase spectrum in Figure 1.14 is completely noisy, which is unexpected. The phase spectrum is noisy
due to fact that the inverse tangents are computed from the ratio of imaginary part to real part of the FFT
result. Even a small floating rounding off error will amplify the result and manifest incorrectly as useful phase
information [5]. To understand, print the first few samples from the FFT result and observe that they are not
absolute zeros (they are very small numbers in the order 10 '), Computing inverse tangent will result in
incorrect results.
>> X(1:5)
1.00-16 *
-0.7286 -0.3637 -0.2501i -0.4809 -0.1579i -0.3602 -0.5579i 0.0261 -0.495i
>> atan2(imag(X(1:5)) , real (X(1:5)))
ans
3.1416 -2.5391 2.8244 -2.1441 -1.5181
‘The solution is to define a tolerance threshold and ignore all the computed phase values that are below the
threshold.
Program 1.16: Extracting phase information from FFT - using a tolerance threshold
X25X;%store the FFT results in another array
Zdetect noise (very small numbers (eps)) and ignore them
threshold = max(abs(X))/10000; %tolerance threshold
X2(abs(x)