PreprintPDF Available
Preprints and early-stage research may not have been peer reviewed yet.

Abstract

This document provides a practical overview of how to design and implement filters with a focus on using Octave and Matlab
Digital Filters A practical guide
David Dorran Page 1
Table of Contents
How to use this series of documents .................................................................................... 2
Introduction and aims of this document ............................................................................. 3
A filtered audio example ....................................................................................................... 4
An introduction to a filter’s frequency response ................................................................. 5
Matlab/Octave code used to create the ‘toy examples’ .................................................. 10
The magnitude response of the audio filter example ..................................................... 15
Magnitude response quiz ................................................................................................. 17
The decibel magnitude scale and logarithmic frequency axis ........................................... 18
The decibel (dB) magnitude scale ................................................................................... 18
The logarithmic frequency axis ........................................................................................ 23
Implementing filters using filter design functions in Matlab/Octave ............................... 25
Filter order ........................................................................................................................27
Filter cut-off frequency (normalised frequency) ............................................................ 29
Normalised Frequency (radians per sample) .............................................................. 32
Filter types ....................................................................................................................... 34
Designing a minimum order filter .................................................................................. 36
Other filter design functions and their benefits ............................................................ 40
Some ‘intuitive’ filters (moving averager, comb filter, DC removal) ................................ 45
Moving averager .............................................................................................................. 45
Comb filter ........................................................................................................................ 51
DC removal (a basic high pass filter) ............................................................................... 53
Linear Time-Invariant (LTI) systems .................................................................................. 55
Linearity ............................................................................................................................ 55
Time-Invariance .............................................................................................................. 58
Transient response of filters ............................................................................................... 60
Why transients always occur at system start-up ............................................................ 63
Digital Filters A practical guide
David Dorran Page 2
How to use this series of documents
Digital Signal Processing Foundations provides a gentle introduction to the world of
DSP. This series of documents deals with topics relevant to DSP and they provide links to
online video content in an effort to make some perhaps tricky concepts easier to
understand for the reader.
If you are completely new to DSP then I’d recommend you take a look at the foundations
document first.
I believe that the approach of integrating text with video takes advantage of the unique
visualisations that video material has to offer with the more in-depth detail and speed of
review that text-based material does. Most of the video material relates to my own
youtube channel, which at the time of writing (2022) had over 17,500 subscribers and 3.5
million views.
I also provide Octave/Matlab code examples throughout the document and I’d encourage
anyone who wants to develop practical DSP skills to download Octave, which is available
free of charge, and implement your ideas.
My intention is to continue this series so as to deal with the major elements of DSP, such
as correlation, the Z-Transform and so on. I’ll post updates to this series at
http://www.pzdsp.com/docs if you want to check out any new additions.
If you find any of this work useful I’d be most grateful if you could cite the relevant
resource when appropriate to provide recognition.
Regards,
David
Digital Filters A practical guide
David Dorran Page 3
Introduction and aims of this document
A digital filter alters a digital signal in a meaningful way. An example is
illustrated in the figure below, whereby a noisy ECG
(electrocardiogram/heart signal) is modified by the digital filter to make
it easier to interpret by a medical professional.
ECG signals can be corrupted by interference from electromagnetic waves
being generated by the multitude of electrical instruments and devices in
hospitals. Removal of this interference can often be easily achieved using
digital filters.
This document provides some straightforward techniques to filter signals and introduces
the terminology required to describe and implement filters. The objective is to provide a
relative newcomer with practical skills that can be applied easily and avoid delving into
theory when possible. Some readers may just need to understand the first audio example
to be able to filter signals, but further insight can be obtained from the remaining sections.
It will help if the reader has read the Digital Signal Processing Foundationsdocument
prior to commencing this one and understand that digital signals are simply a sequence
of numbers that represent a signal of interest, and its often useful to plot these numbers
to make it easier to interpret them, as shown in the example below.
DSP
Filter
Noisy ECG Signal Filtered ECG Signal
This sequence of 100 numbers is a digital
signal which represents a short 20ms
segment of a speech signal:
-11 -6 6 6 13 2 -15 -18 -18 -24 -19 -12 -7 4 44 63
19 -8 -27 -44 -25 14 28 24 20 -2 -22 -15 3 25 20 7
-10 -27 -21 -13 -14 -13 -11 -10 -2 27 63 30 -8 -23 -
35 -26 8 31 21 12 -2 -17 -15 5 22 25 12 -19 -28 -20
-15 -10 -8 -15 -15 -2 27 65 35 -10 -29 -35 -22 8 34
24 6 -8 -17 -11 8 28 24 1 -21 -27 -17 -9 -9 -14 -18 -
15 -1 31 71 32 -18 -38
0 20 40 60 80 100
-50
0
50
100
Sample number
Amplitude
A plot of a quasi-periodic digital signal given
by the numbers to the left
Digital Filters A practical guide
David Dorran Page 4
The Matlab/Octave code used to create the plot above is shown in the code below:
>> x = [-11 -6 6 6 13 2 -15 -18 -18 -24 -19 -12 -7 4
44 63 19 -8 -27 -44 -25 14 28 24 20 -2 -22 -15 3 25 20 7
-10 -27 -21 -13 -14 -13 -11 -10 -2 27 63 30 -8 -23 -35 -26
8 31 21 12 -2 -17 -15 5 22 25 12 -19 -28 -20 -15 -10 -8 -
15 -15 -2 27 65 35 -10 -29 -35 -22 8 34 24 6 -8 -17 -11 8
28 24 1 -21 -27 -17 -9 -9 -14 -18 -15 -1 31 71 32 -18 -
38];
>> plot(x)
>> xlabel('Samples')
>> ylabel('Amplitude')
To get the most out of this document you should be familiar with the frequency-domain
representation of signals as well as discrete systems and difference equations (see “Digital
Signal Processing Foundations”). Having said that, you could probably muddle your way
through without this prior knowledge!
You’ll notice that I use the terms digital filter and discrete system interchangeably
throughout this document. This is simply because they refer to the same thing! I
appreciate that it may be a little confusing but half the battle with any new topic is getting
used to new terminology and how it is used in practice.
The key section in this document is the one entitled “Implementing filters using filter
design functions in Matlab/Octave” and it’s important to remember that all the other
sections are just there to support you being able to implement filters. You might find it
useful just to skim through the other sections and revisit if necessary, to reinforce your
understanding of some of the concepts.
A filtered audio example
Filtering signals can be quite a straightforward process and can be achieved with just a
few of lines of code using tools like Matlab or Octave. The lines of code shown below
‘clean up’ a speech signal, using a digital filter, making it more pleasant to listen to. You
can listen to the recordings by clicking on the relevant links below, and I provide a brief
explanation of the code at pzdsp.com/vid34. Don’t worry if the code seems daunting (skip
it completely if you wish)! I just want to provide a practical example and audio examples
are quite useful because you can easily hear the effect of filtering a signal. Take a listen to
Digital Filters A practical guide
David Dorran Page 5
the input (noisy speech) and output of the filter (filtered speech) to gain an appreciation
as to what filtering is trying to achieve.
>> % Download the noisy speech signal from
http://pzdsp.com/wavs/noisy_speech.wav
>> input = audioread('noisy_speech.wav'); % input is a
sequence of numbers that represents the noisy speech
signal
>> fs = 44100; % The speech signal was sampled at 44100
samples per second i.e. 44.1kHz
>> [b a] = butter(5,0.2,'low'); % Design a 5th order
butterworth low-pass filter. Cutoff frequency
4410Hz=0.2*fs/2 i.e. frequencies above ~4kHz are reduced
>> output = filter(b,a,input); % This line implements the
filter i.e. passes the input through the filter
>> sound(input,fs); % Listen to the input
>> pause(5); % pause for the duration of the input i.e 5
seconds
>> sound(output,fs); % Listen to the output. Also
available at http://pzdsp.com/wavs/filtered_speech.wav
What you should have noticed in this speech example is that high frequency sounds have
been removed from the input recording. Take a listen again if this isn’t obvious!
When filters are being designed they are usually trying to remove certain frequency
components from a signal, but they can also be designed to emphasise particular
frequencies. You might be familiar with an audio equaliser which can be used to reduce
or amplify certain frequency components, e.g. boost bass frequencies, as can be seen (and
heard!) at pzdsp.com/vid35.
A key point to note is that when designing and discussing filters you need to be
comfortable with the concept of the frequency-domain (see pzdsp.com/vid14 and
pzdsp.com/vid15 for video tutorials/demonstrations on this concept).
An introduction to a filters frequency response
A system/filter’s frequency response shows how the system/filter will alter any sinusoidal
waveform (pzdsp.com/vid21). The reason we are so interested in how sinusoidal
waveforms are altered by systems is because any signal can be considered as being a sum
of sinusoidal waveforms, as discussed in “Digital Signal Processing Foundations”. So, if we
Digital Filters A practical guide
David Dorran Page 6
know how any sinusoidal waveform will be altered by a system we can then determine
how the system will alter any signal.
Recall that sinusoidal waveforms have three key parameters: amplitude, phase and
frequency (see pzdsp.com/sinusoids). For the systems described in these notes, you will
find that the frequency of a sinusoidal waveform will never be changed by the system
(a.k.a filter) i.e. if you pass a sinusoidal waveform of 100 Hz through the system you will
get a sinusoidal waveform of 100 Hz out of the system! This is because the systems
described here are all Linear Time-Invariant (LTI) systems, which basically means that
they behave in a very predictable way, and one consequence of using LTI systems is that
a sinusoidal waveforms frequency cannot be altered. See the section entitled Linear
Time-Invariant (LTI) systemsfor more information.
So, if the filters discussed here cannot alter a sinusoidal waveforms frequency, then all
that can be changed is the amplitude (or magnitude) of the sinusoidal waveform and the
phase of the sinusoidal waveform. Consequently, there are two parts to a system’s
frequency response; they are the magnitude response (pzdsp.com/vid22) and the phase
response (pzdsp.com/vid37). The magnitude response of a system shows how the
amplitudes of sinusoidal waveforms are modified while a system’s phase response shows
how the phases are modified.
A system’s magnitude and phase responses are often shown as plots, and it’s very
important to be able to interpret these plots in order to design filters and also to
appreciate how filters will modify signals. In the remainder of this section I’ll run through
some ‘toy examplesusing relatively simple signals that I’ve created (synthesised). If you’d
prefer, you could skip ahead to the next section entitledThe magnitude response of the
audio filter examplefor a real-world example.
The plot below shows the magnitude response of an example system with the horizontal
axis displaying frequency in units of Hertz. The magnitude response shows how the
amplitudes of sinusoidal waveforms will be modified by the system. So, for this example
filter/system, a sinusoidal waveform of frequency 5 Hz will be amplified by approximately
0.6, while a sinusoidal waveform of frequency 60 Hz will be amplified by approximately
2.2, as also illustrated in the time-domain signal plots shown further down.
Note that vertical axis is labelled as ‘Magnitude/ “Amplification Factor”’. The term
“Amplification Factor” is not usually used in practice and ‘Magnitude’ is used frequently
on its own.
Digital Filters A practical guide
David Dorran Page 7
The plot below shows the phase response of the example system. Once again, the
horizontal axis is displayed in units of Hertz. The vertical axis shows the phase angle/shift
in units of degrees. The phase response shows the phase angle imparted on a sinusoidal
waveform by the system. So, for this example filter/system, a sinusoidal waveform of
frequency 5 Hz will have a phase shift of -30° imparted on it i.e. there will be a phase
difference of 30° between the input and the output sinusoidal waveforms (remember that
the frequency of the sinusoidal waveform never changes!). For a sinusoidal waveform of
frequency 60 Hz the phase difference between the input and the output will be 150°.
It can be useful to visualise how sinusoidal waveforms are modified by a system in the
time-domain, as illustrated in the figure below, which depicts the sinusoidal waveforms
being modified by the filter with the frequency response described above. Notice that the
5 Hz waveform is reduced in amplitude by the filter while 60 Hz waveform is increased.
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110
Frequency (Hz)
0
0.5
1
1.5
2
2.5
Magnitude Respons e
Magnitude
"Amplification factor"
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 11 0
Frequency (Hz)
-180
-135
-90
-45
0
45
90
135
180
Phase shift (degrees)
Phase Response
ti me (seconds )
0. 40
A mpli tude
Digital
Filter
input output
5 Hz Sinusoidal Waveforms
ti me (seconds )
0. 40
A mpli tude
Digital Filters A practical guide
David Dorran Page 8
The plots below show the input signals overlaid with the outputs in the time-domain to
make them easier to compare. In particular you should make sure you appreciate the
effect of the phase shift being imparted by the system on the sinusoidal inputs. The 30°
phase shift applied to the 5 Hz components results in the ‘peaks’ of the input and output
being offset by 1/12 of a period (1/12 = 30°/360°). The 135° phase shift applied to the 60 Hz
components results in the ‘peaks’ of the input and output being offset by ~2/5 of a period
(~2/5 = 150°/360°).
Let’s consider one more ‘toy example’ to reinforce how a system’s frequency response can
be used to determine how more complex signals will be modified by the system. In this
last example the input to the filter will be the sum/addition of two sinusoidal waveforms
of different frequencies; one of 5 Hz and the other of 60 Hz. The amplitude of the 5 Hz
component is ten times the amplitude of the 60 Hz component. The plots below show the
time-domain and frequency-domain representations of the input signal.
ti me (seconds )
0. 40
A mpli tude
Digital
Filter
input output
60 Hz Sinusoidal Waveforms
ti me (seconds )
0. 40
A mpli tude
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4
Tim e (seconds)
-5
0
5
Amplit ude
5 Hz input and output sinusoidal w aveforms
5 Hz input
5 Hz ouput
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4
Tim e (seconds)
-1
0
1
Amplit ude
60 Hz input and output sinusoidal w aveforms
60 Hz input
60 Hz ouput
Digital Filters A practical guide
David Dorran Page 9
Because the filter is an LTI system (and therefore behaves in a very predictable way) the
output to this more complex input signal will be the same as the sum of the outputs when
each individual sinusoidal waveform is applied. We have already seen the individual
outputs when 5 Hz and 60 Hz sinusoidal waveforms have been applied, so we should be
able to predict how this more complex input will be modified. The 5 Hz component will
be reduced in amplitude while the 60 Hz component will be increased in amplitude. Also,
a more significant phase shift will be imparted on the 60 Hz component. You should try
and visualise what the output waveform/signal might look like before looking at the plot
below. Notice that, in the time-domain, the high frequency oscillations have increased in
amplitude and how the ‘underlying’ low frequency oscillation has decreased.
It’s also useful to examine the difference between the magnitude frequency content of
the input and the output. Notice how the magnitude content of the output is the same as
the magnitude content of the input multiplied by the magnitude response of the system.
The 5 Hz component has been amplified by 0.6 while the 60 Hz component has been
amplified by 2.2.
In this section, I have focused in on two frequency components i.e. 5 Hz and 60 Hz,
however it’s important to realise that the sinusoidal waveforms of any frequency will, of
course, be modified by the example system.
00.1 0.2 0.3 0.4
Tim e (seconds)
-5
0
5
Amplitude
Signal input time-domain e volution
0
2
4
6
Sinus oid Amplitude
Signal input frequency content
020 40 60 80 100
Frequency (Hz)
0 0.1 0.2 0.3 0.4
Tim e (seconds)
-5
0
5
Amplitude
Signal output time-domain evolution
0
2
4
6
Sinus oid Amplitude
Signal output frequency content
020 40 60 80 100
Frequency (Hz)
Digital Filters A practical guide
David Dorran Page 10
Matlab/Octave code used to create the ‘toy examples’
It’s not necessary to fully understand the code provided here, however many readers may
benefit from being able to modify the code to verify their understanding of a systems
frequency response is correct. This code is very closely related to the examples provided
above, with some subtle differences, as explained further on. The digital filter from the
previous section is given by the following difference equation, with the corresponding
signal flow diagram also shown:
y[n] = 0.005x[n] + 2.7949y[n-1] - 2.7359y[n-2] + 0.934y[n-3]
The b coefficient of the system is 0.005, while the a coefficients are 1, -2.782, 2.71 and -
0.921 (note the change of sign on the a coefficients see pzdsp.com/vid20 for an
explanation on why this happens). The frequency response of the system can be obtained
and plotted using the following lines of code:
>> b = [0.005];
>> a = [1 -2.7949 2.7359 -0.934];
>>
>> fs = 1000; % sampling frequency
>> fnyq = fs/2; % Nyquist frequency
>> H = freqz(b,a,4000); % freqz determines the frequency
response of a system. The 4000 parameter controls the
frequency resolution
>>
>> subplot(2,1,1)
>> fax_h = [0:length(H)-1]/length(H)*fnyq;
>> plot(fax_h, abs(H))
>> xlabel('Frequency (Hz)');
>> ylabel('Magnitude')
Digital Filters A practical guide
David Dorran Page 11
>> xlim([0 110])
>> title('Magnitude Response')
>>
>> subplot(2,1,2)
>> plot(fax_h, angle(H)/pi*180)
>> xlabel('Frequency (Hz)');
>> ylabel('Phase shift (degrees)')
>> xlim([0 110])
>> title('Phase Response')
Now let’s synthesise and filter the three signals described earlier using the following code:
>> fs = 1000;
>> t = 0:1/fs:0.4-1/fs;
>> x1 = 5*cos(2*pi*5*t +pi/4); % 5 Hz sinusoidal waveform
>> x2 = 0.5*cos(2*pi*60*t -pi/4); % 60 Hz sinusoidal
waveform
>> x = x1+x2; % the more complex signal
>> % Filter the signals using the three lines below
>> y1 = filter(b,a,x1);
>> y2 = filter(b,a,x2);
>> y = filter(b,a,x);
Then take a look at the time-domain inputs and outputs:
>> subplot(3,1,1)
>> plot(t, x1);
010 20 30 40 50 60 70 80 90 100 110
Frequency (Hz)
0
0.5
1
1.5
2
Magnitude
Magnitude Response
010 20 30 40 50 60 70 80 90 100 110
Frequency (Hz)
-200
-100
0
100
200
Phase shift (degrees)
Phase Response
Digital Filters A practical guide
David Dorran Page 12
>> hold on; plot(t, y1);
>> ylim([-5.5 5.5])
>> xlabel('Time (seconds)')
>> ylabel('Amplitude');
>> title('5 Hz input and output sinusoidal waveforms')
>> legend({'input', 'output'})
>> subplot(3,1,2)
>> plot(t, x2);
>> hold on; plot(t, y2);
>> ylim([-5.5 5.5])
>> xlabel('Time (seconds)')
>> ylabel('Amplitude');
>> title('60 Hz input and output sinusoidal waveforms')
>> legend({'input', 'output'})
>> subplot(3,1,3)
>> plot(t, x);
>> hold on; plot(t, y);
>> ylim([-5.5 5.5])
>> xlabel('Time (seconds)')
>> ylabel('Amplitude')
>> title('Input and ouput of a signal comprised of two
sinusoidal waveforms')
>> legend({'input', 'output'})
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4
Tim e (seconds)
-5
0
5
Amplit ude
5 Hz input and output sinusoidal w aveforms
input
output
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4
Tim e (seconds)
-5
0
5
Amplit ude
60 Hz input and output sinusoidal w aveforms
input
output
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4
Tim e (seconds)
-5
0
5
Amplit ude
Input and ouput of a signal comprised of two sinusoidal w aveforms
input
output
Digital Filters A practical guide
David Dorran Page 13
I’d like you to notice that the first 0.1 seconds or so of the filter outputs look a little
unusual, and perhaps not as first expected (on close inspection you’ll even see some
unusual features up to 0.2 seconds). This is due to what is known as the transient response
of a filter and it takes some time for a filter to reach steady-state. I provide an explanation
of this phenomenon a little later in the section entitledTransient response of filters”.
This is an issue will affect practically all filters and is something you need to be aware of
as a practicing DSP engineer.
It can also be useful to explicitly verify that the output of the more complex signal is the
same as the sum of the filtered individual sinusoidal waveforms (it’s always nice to try and
verify theory through practice!).
>> plot(t, y,'Linewidth',3,'Color','black');
>> hold on
>> plot(t, y1+y2,'Linewidth',1,'Color','green');
>> xlabel('Time (seconds)')
>> ylabel('Amplitude')
>> legend({'Output y', 'Output y1+y2'})
Finally, we can view the magnitude frequency content of the input and output of the more
complex signal using this code:
>> subplot(1,2,1)
>> fax = [0:length(x)-1]/length(x)*fs;
>> plot(fax,abs(fft(x))/(length(x)/2))
>> xlim([0 110])
>> xlabel('Frequency (Hz)');
>> ylabel('Sinusoid Amplitude')
>> title('Input frequency content')
>> subplot(1,2,2)
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4
Tim e (seconds)
-5
0
5
Amplitude
Output y
Output y1+y2
Verifying output equals sum of two individual ouputs
Digital Filters A practical guide
David Dorran Page 14
>> plot(fax,abs(fft(y))/(length(y)/2))
>> xlim([0 110])
>> ylim([0 6])
>> xlabel('Frequency (Hz)');
>> ylabel('Sinusoid Amplitude')
>> title('Output frequency content')
You’ll notice the ‘triangular’ shape associated with each of the two frequency components.
This is due to the way Matlab and Octave plot data, whereby data points are simply joined
by a straight line and there are a limited number of data points i.e. in this case there are
only data points every 2.5 Hz along the frequency axis (the so-called bin frequency
resolution is given by the sampling frequency (1000 Hz) divided by the length of the signal
(400 samples) see The Discrete Fourier Transform - A practical approach”). So, the
datapoints at 0 Hz, 2.5 Hz, 5 Hz, 7.5 Hz and 10 Hz will form a triangle (see plot below)
since the magnitudes of the datapoints are all zero except for the datapoint at 5 Hz which
has a magnitude of 5. Using the ‘stem’ function in place of the ‘plot’ function can remove
this issue, however it does introduce other problems!
020 40 60 80 100
Frequency (Hz)
0
2
4
6
Sinus oid A mplitude
Input frequency content
020 40 60 80 100
Frequency (Hz)
0
2
4
6
Sinus oid A mplitude
Output frequency content
0 2.5 5 7.5 10 12.5
Frequency (Hz)
0
2
4
6
Sinus oid Amplitude
Input frequency content (0 - 12.5 Hz)
Digital Filters A practical guide
David Dorran Page 15
You’ll also notice that the output shows that low frequencies that were zero at the input
are no longer zero, which can seem odd since it implies the filter has created new
frequency components. This issue is related to the transient response of a filter which is
discussed in the section entitled “Transient response of filters”.
The magnitude response of the audio filter example
The figure below shows the magnitudes of the frequency content of both the input signal
(noisy speech) and the output signal (filtered speech) from the previous audio example.
Notice that the filtered speech (output signal) has no significant frequency content above
5 kHz, as these frequencies have been effectively removed by the digital filter. All the noisy
components lie above 5 kHz, while the speech is mostly below 5 kHz. You should try to
relate these visual plots of both signals frequency content to what you can hear when you
listen to the audio signals. Our ability to perceive different frequencies of sounds using
our hearing system (ears, basilar membrane, cochlea, brain, etc) is pretty amazing and
something that you take advantage of when trying develop an intuition with frequency-
domain concepts.
Also shown in the plot is the magnitude response of the filter (a.k.a. discrete system),
depicted as a thicker line on the plot (note that the right vertical axis is associated with
the magnitude response while the left vertical axis is associated with the frequency
content of the input and output in this plot). This type of filter is called a low-pass filter
i.e. low frequency components are allowed to pass through the filter/system and high
0 5 10 15 20
Frequency (kHz)
0
100
200
300
400
500
Magnitude content of input and output s ignals
0
0.2
0.4
0.6
0.8
1
1.2
1.4
Magnitude response of system
Input Frequencies
Output Frequencies
Filter Magnitude Response
1
Digital Filters A practical guide
David Dorran Page 16
frequencies are reduced/attenuated. You should notice how, at each frequency, the
magnitudes of the frequency content of the input is multiplied by the magnitude response
of the filter to produce the magnitudes of the frequency content of the output. For low
frequencies the input (blue) and output (orange) frequencies are the same, since for these
frequencies the input frequencies are multiplied by 1 (note that I made the input
frequencies plot line is slightly thicker so it would be visible behind the output
frequencies ‘plot line’).
The following code can be used to generate the plots above. It’s not necessary to
understand this code and is just provided for the interested reader. A video explanation
on plotting a signals frequency content can be found at pzdsp.com/vid36.
>> % Download the noisy speech signal from
http://pzdsp.com/wavs/noisy_speech.wav
>> [input fs] = audioread('noisy_speech.wav'); % input is
a sequence of numbers that represents the noisy speech
signal
>> [b a] = butter(5,0.2,'low'); % Design a 5th order
butterworth low-pass filter. Cutoff frequency
4410Hz=0.2*fs/2 i.e. frequencies above ~4kHz are reduced
>> output = filter(b,a,input); % This line implements the
filter i.e. passes the input through the filter
>> fax = [0:length(input)-1]/length(input)*fs/1000; %
frequency axis in kHz
>> plot(fax, abs(fft(input)),'Linewidth',1.5) % frequency
content of input
>> hold on
>> plot(fax, abs(fft(output))) %frequency content of
output
>> ylabel('Magnitude content of input and output signals')
>> xlabel('Frequency (kHz)')
>>
>> H=freqz(b,a); % frequency response of system
>> fax_H = [0:length(H)-1]/length(H)*fs/2/1000; %
frequency axis. Divide by 100 to change to kHz.
>>
>> yyaxis right
>> plot(fax_H, abs(H),'Linewidth',4)
>> ylabel('Magnitude response of system')
>> xlim([0 fs/2/1000]) % Display positive frequencies only
>> legend('Input Frequencies', 'Output Frequencies',
'Filter Magnitude Response')
Digital Filters A practical guide
David Dorran Page 17
Magnitude response quiz
Here’s a problem for you to work on to ensure you understood the concept of frequency
response and frequency content. The plots in the table below show the magnitudes of the
frequency content of 5 signals in the column to the left, labelled 1,2,3,4, and 5. Each of the
signals are filtered by a different system, with the frequency response of the system used
to filter each signal aligned to the right of the signal being filtered, in the centre column.
The plots in right column show the frequency content of the output of the systems,
however they are not aligned with the input signals. Can you determine which input
signals (1, 2, 3, 4, 5) corresponds to which output signals (A, B, C, D, E)? The answer is
provided below, but you should really try to work it out for yourself first!
Answers: 1→C; 2→A;3→E;4→B;5→D
Digital Filters A practical guide
David Dorran Page 18
The decibel magnitude scale and logarithmic frequency axis
The frequency response of a system and frequency content of a signal are often plotted
using different axes than the ones shown so far. The choice of axes can vary from industry
to industry or even just be influenced by personal preference. This section discusses two
aspects of this i.e. dB magnitude scale and the logarithmic frequency axis, while the video
at pzdsp.com/vid36 can provide some additional insight. While it’s useful to be aware of
the different axes scales that can be used it is far more important that you appreciate the
previous section and be able to interpret the magnitude and phase response. I’d be
inclined to skim this section and revisit as needed. The most important takeaway from
this section is to appreciate how the dB scale relates to the linear scale, since this is
required in order to use some Octave/Matlab filter design functions.
The decibel (dB) magnitude scale
A common and alternative way to plot the frequency response is to display the magnitude
axis in units of decibels (dB scale). The figure below shows an example frequency response
for two cases: magnitude on a linear scale (as used up to this point in this document) and
on a dB scale. Note that the frequency responses are associated with the same filter in
both cases, only the scale has changed.
You’ll notice that the plots increase and decrease at the same frequencies but the rate of
increase and decrease has changed; for amplification factors less than 1 the rate of increase
and decrease is steeper in the dB plot (see frequencies from 20 Hz to 30 Hz, for example),
010 20 30 40 50 60 70 80 90 100
Frequency (Hz)
0
1
2
3
4
Magnitude
Amplificat ion Fac tor
Magnitude Response (linear)
010 20 30 40 50 60 70 80 90 100
Frequency (Hz)
-20
-10
0
10
20
Magnitude (dB)
Magnitude Response (dB)
Digital Filters A practical guide
David Dorran Page 19
while for amplification factors greater than 1 the rate of increase and decrease has been
reduced (see frequencies from 70 Hz to 80 Hz, for example).
I’ll explain the dB scale in more detail shortly but for the moment just note that 0 dB
corresponds to an amplification factor of 1. For example, you can see from the plots that
the frequencies from 0 to 5 Hz are neither increased significantly (amplified) or decreased
significantly (attenuated) by the filter. This range of frequencies is said to have
approximately 0 dB of gain. Also note that a positive dB value corresponds to frequencies
being amplified, while negative dB values correspond to frequencies being reduced.
I’d like you to notice that the amplification factor at 25 Hz is approximately 0.25, while
the amplification factor at 75 Hz is approximately 4. So, at 25 Hz frequencies will be
reduced (or attenuated) by a factor of 4 while at 75 Hz frequencies will be increased (or
amplified) by a factor of 4.
If you look at the linear magnitude response above, the amplification by a factor of 4 (at
75 Hz) is visually more significant than the attenuation by a factor of 4 (at 25 Hz). Contrast
this with the dB Magnitude response, where the response at 25 Hz is a value of -12 dB and
at 75 Hz it is +12 dB. When we plot on the dB scale the ratio of amplification and
attenuation visually receive the same weighting, which is not the case when using the
linear scale.
The following second example highlights this issue. Once again, the plots below are
associated with the same filter i.e. the magnitude responses are the same, but are plotted
using a different scale (the conversion from one scale to another is described later).
Digital Filters A practical guide
David Dorran Page 20
In the linear magnitude response above it is clear that frequencies of 75 Hz are being
amplified, and you can also see that some frequencies are being attenuated, particularly
between 20 and 35 Hz. However, it’s not clear how much these frequencies are being
attenuated, as the detail is being ‘drowned out’ by the significant amplification at 75 Hz
when using the linear scale. However, when the frequency response is viewed using a dB
scale we can see how the lower frequencies are being attenuated much more clearly. It’s
now obvious that frequencies of 25 Hz and 31 Hz will be significantly attenuated. In fact,
frequencies of 25 Hz will be reduced by a factor of 1000 (equivalent to -60 dB, see table
below) while frequencies of 75 Hz are only being amplified by a factor of 18.
The code used to generate the plots above is included below for the interested reader. Feel
free to skip this though!
>> b = [ 1.0471 0.9424 0 0 0.6570 0.5913];
>> a = [ 1 1.3435 0.9025];
>> % UNCOMMENT THE NEXT TWO LINES FOR THE SECOND EXAMPLE
>> % b = [1 -0.3581 0.0478 1.0321 0.6242 -0.15 0.1266
0.71];
>> % a = [1 1.3718 0.9409];
>> fs = 200;
>> fnyq = fs/2;
>> H = freqz(b,a);
>> subplot(2,1,1)
>> fax_H = [0:length(H)-1]/length(H)*fnyq;
>> plot(fax_H, abs(H))
>> xlabel('Frequency (Hz)');
010 20 30 40 50 60 70 80 90 100
Frequency (Hz)
0
5
10
15
20
Magnitude
Ampli ficat ion Fac tor
Magnitude Response (linear)
010 20 30 40 50 60 70 80 90 100
Frequency (Hz)
-60
-40
-20
0
20
Magnitude (dB)
Magnitude Response (dB)
Digital Filters A practical guide
David Dorran Page 21
>> ylabel({'Magnitude' 'Amplification Factor'})
>> title('Magnitude Response (linear)')
>> subplot(2,1,2)
>> plot(fax_H, 20*log10(abs(H)))
>> xlabel('Frequency (Hz)');
>> ylabel({'Magnitude (dB)'})
>> title('Magnitude Response (dB)')
Before getting into any detail on the dB scale it can be useful just be able to relate the dB
scale to the linear scale. The equation to convert from a linear scale to a dB scale is:
 =20 log()
The table below shows some examples of dB equivalent values of linear scale values.
Knowing these examples will be very helpful and I would encourage you to make a mental
note of these corresponding values.
Linear Scale
dB Scale
1
0 dB
√2
approx. 3 dB
2
approx. 6 dB
10
20 dB
100
40 dB
1000
60 dB
1/√2
approx. -3 dB
½
approx. -6 dB
1/10
-20 dB
1/100
-40 dB
1/1000
-60 dB
The terms amplifying (increasing) and attenuating (decreasing) are also used frequently
and it can be useful to relate the dB scale to the linear scale using this terminology. Here
are some examples:
amplifying a signal by 20 dB is the same as multiplying it by 100
attenuating a signal by 6 dB is the same as multiplying it by ½
attenuating a signal by 40 dB is the same as dividing it by 100
amplifying a signal by -60 dB is the same as attenuating it by 60 dB
Applying 0 dB of gain to a signal means that it is unchanged
Digital Filters A practical guide
David Dorran Page 22
In general decibels are used as a way of showing the ratio between two numbers. The
decibel unit is defined to be
10 log 1
2 
For example, consider the numbers 0.5 and 50 then the ratio of 0.5 to 50 is 1 : 100. This can
be expressed in dB as being a ratio of -20 dB i.e.
10 log 0.5
50 = 10log 0.01 =20 
The numbers 3 and 300 have the same ratio i.e. 1 : 100 and so the ratio of 3 to 300 is also -
20 dB.
Note that the multiplier of 10 in the equation above is not a typo (20 was used earlier and
it’s not really that important to know why but if you really need to know then please
read on!). The reason a multiplier of 20 was used when calculating the values in the table
shown earlier is because traditionally the dB scale as used to show the ratio of the
electrical power into a system to the electrical power out of system.
10 log  
  
When we are measuring signals, the signals are often converted to voltage signals and
then converted into a numerical value by an analog to digital converter. So, our signals
are often voltage signals, not power signals. However, voltage squared is proportional to
power in electrical systems, so
10 log  
   = 10 log ( )
( )  =10 log  
 

Using the logarithm rule that log=. log, we can therefore show that
10 log  
   = 20 log  
  
i.e. dB scaled voltage signals are scaled by 20 (rather than 10) to make them comparable
to power signals.
Digital Filters A practical guide
David Dorran Page 23
The logarithmic frequency axis
It’s quite easy for us to use our hearing system to tell the difference between a 200 Hz tone
and a 210 Hz tone. However, you find that its quite difficult to differentiate a 1000 Hz tone
from a 1010 Hz tone, even though there is 10 Hz of a difference in both cases. You can
create different frequency tones (sinusoidal audio signals) using the code below.
>> fs = 44100;
>> t = 0:1/fs:1;
>> tone_210Hz = cos(2*pi*210*t);
>> tone_200Hz = cos(2*pi*200*t);
>> tone_1000Hz = cos(2*pi*1000*t);
>> tone_1010Hz = cos(2*pi*1010*t);
>> sound(tone_200Hz,fs)
As frequency increases our ability to distinguish between specific frequencies decreases.
For example, our ability to differentiate between 1,000 Hz and 1,100 Hz is about the same
as our ability to differentiate a 10,000 Hz tone as a 11,000 Hz tone. In other words, there is
a logarithmic relationship i.e. log10(1,000/1,100) = log10(10,000/11,000).
To take this relationship into consideration audio engineers will often plot the frequency
response using a logarithmic frequency axis, as shown in the example below. The top plot
is the frequency response of a system plotted against a logarithmic frequency axis, while
the bottom plot is the same frequency response plotted against a linear frequency axis.
Both plots use a dB magnitude scale.
Notice that the spacing along the logarithmic frequency axis is the same for the same ratio
of frequencies. For example, the spacing between 10 Hz and 100 Hz is the same as the
spacing from 100 Hz to 1000 Hz, which is also the same as the spacing from 1000 Hz to
1000 Hz. The figure also highlights the significant attenuations at 250 Hz, 500 Hz, 2500
Hz, 5000 Hz and 10000 Hz. Notice that the spacing, on the logarithmic axis, is the same
between the attenuations at 250 Hz and 2500 Hz as the spacing between the attenuations
at 500 Hz and 5000 Hz, since the ratios of these frequencies are the same (250/2500 =
500/5000). The same is true for the spacing between the attenuations at 250 Hz and 500
Hz and the spacing between the attenuations at 5000 Hz and 10000 Hz, since 250/500 =
5000/1000.
Digital Filters A practical guide
David Dorran Page 24
The code below can be used to generate the above plots:
>> b = [1 -4.6154 9.4861 -11.6567 9.2406 -3.6996
-1.7127 3.8719 -2.5468 0.6329];
>> a = [ 1 -5.2616 12.9212 -20.1702 22.6857 -19.1004
11.6067 -4.4978 0.8166];
>> fs = 20000;
>> fnyq = fs/2;
>> H = freqz(b,a, 10000);
>> fax_H = [0:length(H)-1]/length(H)*fnyq;
>> subplot(2,1,1)
>> semilogx(fax_H, 20*log10(abs(H)))
>> xlabel('Frequency (Hz)');
>> ylabel({'Magnitude (dB)'})
>> title('Magnitude Response (dB)')
>> subplot(2,1,2)
>> plot(fax_H, 20*log10(abs(H)))
>> xlabel('Frequency (Hz)');
>> ylabel({'Magnitude (dB)'})
>> title('Magnitude Response (dB)')
While the log frequency axis is linked to the way in which we perceive sounds, it’s also
commonly used in non-audio contexts. Using the log frequency axis together with a dB
scale magnitude axis is also useful because complex filters can be quickly sketched by
engineers using straight line segments, in what is referred to as an asymptotic
approximation of a Bode plot. In the example below, the magnitude response of a first
order system (blue curve) is approximated by two straight line segments (black lines). The
10
0
10 =10
1
10 =100
2
10 = 1000
3
10 =10000
4
Frequency (Hz)
-10
-5
0
5
Magnitude (dB)
Magnitude Response (dB) Logarithmic Freque ncy Axis
01000 2000 3000 4000 5000 6000 7000 8000 9000 10000
Frequency (Hz)
-10
-5
0
5
Magnitude (dB)
Magnitude Response (dB) Linear Frequency Axis
Digital Filters A practical guide
David Dorran Page 25
interested reader should identify another resource on this topic for a more detailed
explanation.
Implementing filters using filter design functions in Matlab/Octave
Matlab/Octave provide built-in functions to design four basic filter types, as depicted in
the figure below:
Lowpass allows low frequencies through; rejects high frequencies.
Highpass allows high frequencies though; rejects low frequencies.
Bandpass allows a certain range of frequencies through and rejects frequencies
outside that range
Bandstop (or band-reject) rejects a certain range of frequencies and allows
frequencies outside that range to pass.
The most straightforward filter design function to use is the butter function, named after
the British engineer Stephen Butterworth (18851958).
As shown in the code below, the butter function takes three input parameters (the filter
type, the order and the cut-off frequency explained further on) and returns the b and a
coefficients that describe the discrete system, which can then be used to filter a signal.
The video at pzdsp.com/vid38 runs through how to use the function.
>> [b a] = butter(1, 0.2,'low');
10
-1
10
0
10
1
10
2
Frequency (Hz)
-30
-25
-20
-15
-10
-5
0
5
Magnitude (dB)
Magnitude Response of 1st order system with Asymtotic Approximation shown
Digital Filters A practical guide
David Dorran Page 26
The function’s three input parameters (order (value = 1), cut-off frequency (value = 0.2),
and type (value = ‘low’)) are explained later but it’s worth noting that a single line of code
is all you need to design a filter. The following line of code shows an example of filtering
a signal, where the input to the filter is a sequence of random numbers created using the
built-in rand function.
>> x = rand(1,20000);
>> y = filter(b,a,x);
The first line will create a variable x that contains 20,000 random numbers that have a
value that lie between 0 and 1. The second line uses the built-in function called filter to
filter the signal x using the b and a coefficients returned by the butter function earlier.
It can be useful to listen to the input and output, and if you use the code below you’ll hear
that high frequencies have been removed.
>> sound(y, 10000)
>> pause(2.5)
>> sound(x, 10000)
0f
Nyquist
Frequency
0
1
Magnitude
Low-p a ss fi l te r
0f
Nyquist
Frequency
0
1
Magnitude
High-pa ss f i lt e r
0f
Nyquist
Frequency
0
1
Magnitude
Band-p a ss fi l te r
0f
Nyquist
Frequency
0
1
Magnitude
Band-stop fil te r
Digital Filters A practical guide
David Dorran Page 27
The following sections provide some detail on the three parameters but the following
summary, together with reader experimentation, may suffice in many cases:
The first parameter, the filter order, controls the steepness (roll-off rate) of the
frequency response curve. A higher order results in a steeper curve and requires
more computations to implement
The second parameter, the cutoff-frequency, controls where the frequency
response starts to curve. The value lies between 0 and 1, with 1 corresponding to
Nyquist frequency.
The third parameter specifies the filter type i.e. ‘low’ lowpass; ‘high’
highpass; ‘stop’ bandstop; ‘bandpass’ bandpass. When designing a
bandstop or bandpass filter two cutoff-frequencies must be specified e.g. [b a]
= butter(1, [0.25 0.6],'stop');
Filter order
If you run the code [b a] = butter(1, 0.2,'low'); you’ll find that the b
coefficients are [0.2452 0.2452] and the a coefficients are [1 -0.5095]. This corresponds
to the difference equation and signal flow diagram shown below.
y[n] = 0.2452x[n] + 0.2452x[n-1] + 0.5095y[n-1]
The code [b a] = butter(1, 0.2,'low'); designs a first order filter, where the
order (first parameter) is associated with the number of b and a coefficients returned by
the function. If the order is 1 then there are 2 b coefficients and 2 a coefficients. If the order
is 2 then there 3 b coefficients and 3 a coefficients. In general, if the order is n there are
n+1 b and a coefficients.
The filter order affects the ‘roll-off’ rate of the filter, with higher order filters having a
faster roll-off rate, as shown in the figure below. The roll-off rate refers to how quickly
Digital Filters A practical guide
David Dorran Page 28
the frequency response goes from high to low, or the steepness of the curve in the
magnitude response.
You should notice that all three filters pass through the same point, at 0.2 π radians per
sample, which is the cut-off frequency for all three filters (the code used to create the plot
is shown below). The higher order filter reduces higher frequencies more significantly and
also preserves lower frequencies to a greater extent, and in a lot of cases this type of
response is desirable i.e. keeping low frequencies unchanged while reducing high
frequencies significantly. However, higher order filters require more computations (more
additions and multiplications) to implement and can take longer to execute on a
computer (or microcontroller). Digital filter designers usually trying to determine the
lowest order filter to achieve the desired effect (see the section on Designing a minimum
order filter).
Another reason to use a lower order filter is because filters with a slower roll-off rate have
a faster transient response (see the section entitled “Transient response of filters”). For
certain applications a fast transient response is desirable. A problem that often emerges
is that a fast roll-off rate is also desirable and the filter designer is often looking for the
best trade-off between a roll-off rate and transient response. Unfortunately, it’s impossible
to have both a fast roll-off rate and a fast transient response, since increasing one
inevitably decreases the other.
The following code can be used to produce the previous plot (for the interested reader).
>> [b1 a1] = butter(1, 0.2,'low');
>> H1 = freqz(b1,a1);
Digital Filters A practical guide
David Dorran Page 29
>> fax = [0:length(H1)-1]/length(H1);
>> plot(fax,abs(H1))
>> hold on
>> [b2 a2] = butter(2, 0.2,'low');
>> H2 = freqz(b2,a2);
>> plot(fax,abs(H2))
>> [b5 a5] = butter(5, 0.2,'low');
>> H5 = freqz(b5,a5);
>> plot(fax,abs(H5))
>> title({'Frequency response of 3 filters of different
order','Cut-off frequency 0.2 radians per sample'})
>> ylabel('Magnitude')
>> xlabel('Frequency (x \pi rads/sample)')
>> legend('1^{st} order filter', '2^{nd} order
filter','5^{th} order filter')
Filter cut-off frequency (normalised frequency)
The second function parameter in the code [b a] = butter(1, 0.2,'low');
specifies the cutoff-frequency of the filter, which in this case is a value of 0.2. If the cutoff-
frequency value is increased then a wider range of low frequency components will be
passed through the low-pass filter.
The cut-off frequency always has a value between 0 and 1, where 0 corresponds to a 0 Hz
and 1 corresponds to the Nyquist frequency, which is half the sampling frequency of the
signal you are filtering. The plots below show the frequency response of two 12th order
butterworth filters with cutoff-frequencies of 0.4 and 0.65. Notice how the frequency
response associated with the 0.65 cutoff-frequency will allow a greater range of
frequencies to pass though the filter relatively unchanged. Also notice the transition of
the frequency response curve from a value of 1 to a value of zero is in the region 0.45 and
0.65 for the blue and red curves, respectively.
Digital Filters A practical guide
David Dorran Page 30
More specifically the cutoff-frequency specifies the point at which the curve will pass
through a value of 0.7071 = 1/2, which equates to approximately -3 dB (20log10(1/2) = -
3.0103). For this reason, the cutoff-frequency is also often referred to as the 3 dB frequency.
This can be seen more clearly in the plot below (also shown earlier) which shows the
magnitude response of filters of different order all passing though the same point at a
magnitude of 0.7071 and frequency 0.2 radians per sample.
It’s useful to note that digital filters are not designed only to work for one specific
sampling frequency. So, for two very different scenarios the same filter could be used to
achieve the desired effect. For example, consider a situation where an ECG (heart signal),
sampled at 120 Hz, has been corrupted by 50 Hz noise and a second situation where a
speech signal sampled at 32 kHz has a perceptually annoying artefact at 13 kHz. For both
of these situations the same digital filter can improve the quality of the signal, as shown
Digital Filters A practical guide
David Dorran Page 31
using the code below. This is because the artefact/noise in both signals occur in the same
region relative to the Nyquist rate (which is half the sampling rate) i.e. 50/60 = 0.8333 for
the ECG signal and 13,000/16,000 = 0.8125 for the speech signal. This fact can seem odd
to those with experience of analogue filters, since for the analogue case completely
different filter components would be required in both situations. However, when you start
to think about it, a digital filter is just a sequence of multiplications and additions and the
knowledge of sampling rate isn’t required to implement the filter (the behaviour of
components of electrical analogue filters, such as capacitors and inductors, are dependent
on frequency though).
>> % Files used available at http://pzdsp.com/wavs
>> [noisy_speech fs_speech] =
audioread('noisy_speech2.wav');
>> noisy_ecg = load('noisy_ecg.txt');
>> fs_ecg = 120; % The ecg signal was sampled at 120 Hz
>>
>> [b a] = butter(16, 0.7,'low');
>> % Filter both signals with the same filter
>> speech_op = filter(b,a, noisy_speech);
>> ecg_op = filter(b,a, noisy_ecg);
>>
>> subplot(2,1,1)
>> plot(noisy_ecg(1:1400));
>> xlabel('Samples');
>> ylabel('Electrical Activity');
>> title('Noisy ECG signal')
>> subplot(2,1,2)
>> plot(ecg_op(1:1400));
>> xlabel('Samples');
>> ylabel('Electrical Activity');
>> title('Clean ECG signal')
>> sound(noisy_speech, fs_speech)
>> pause(4)
>> sound(speech_op, fs_speech)
Digital Filters A practical guide
David Dorran Page 32
It can take some time to appreciate why digital filters can work for signals sampled at
different rates, and the section entitled “Some ‘intuitive’ filters (moving averager, comb
filter, DC removal)” may help you appreciate this.
Normalised Frequency (radians per sample)
When working with digital filters, frequency is typically expressed in units of radians per
sample rather than frequency in Hertz (or radians per second).
To become more familiar with this way of expressing frequency it can be useful to refer to
some examples. The sinusoidal waveforms plotted below have a frequency of π/4 radians
per sample and π/16 radians per samplenote that the sample points are shown as red
dots and the blue line is just a curve fitted (interpolated) between the samples to make it
easier to visualise the waveforms.
As explained at pzdsp.com/sinusoids, there are 2π radians in a complete cycle (one
period) of a sinusoidal waveform so for the sinusoid of frequency π/4 radians per sample
it takes 8 samples to complete once cycle and for the sinusoid of frequency π/16 samples
per cycle it takes 32 samples.
0200 400 600 800 1000 1200 1400
Samples
-1
0
1
2
Electrical Activity
Noisy ECG signa l
0200 400 600 800 1000 1200 1400
Samples
-1
0
1
Electrical Activity
Clean ECG signal
Digital Filters A practical guide
David Dorran Page 33
You may be wondering what the frequency of the sinusoids shown above are in units of
Hertz (most people are more comfortable with units of Hertz that radians per sample!).
The answer to this question is “It depends on the sampling rate!”. The sampling rate
determines the time duration between samples (i.e. the sampling interval which is equal
to the reciprocal of the sampling rate) so if it takes a sinusoidal waveform 8 samples to
complete one cycle and the sampling rate is 10 Hz then the time to complete one cycle is
0.8 seconds, which means the frequency of the sinusoidal waveform is 1/0.8 = 1.25 Hz. It’s
very important to appreciate that in order to express the frequency content of a signal in
Hertz you need to the sampling rate used to capture the signal.
You will have noticed that the frequency domain plots shown earlier have a frequency axis
with a range of either 0 to Nyquist frequency, or from 0 to 1. The reason the upper limit
is Nyquist frequency (which is equal to half the sampling frequency) is because any
frequencies above Nyquist frequency would suffer from a phenomenon known as aliasing
(link to vid). This aliasing phenomenon is generally not desirable and frequencies above
Nyquist frequency are usually ensured to be insignificant before a signal is sampled. For
this reason, the frequency range of interest is typically from 0 up to Nyquist frequency.
When the frequency axis range is from 0 to 1 you will notice that the units are shown as being
π radians per sample. The highest frequency component is therefore π radians per sample (also,
the lowest frequency is 0 radians per sample and a frequency component in the middle of the
frequency axis would equate to π/2 radians per sample). The plot below shows a sinusoidal
waveform of frequency π radians per sample, which you’ll notice has two samples per cycle. This
Digital Filters A practical guide
David Dorran Page 34
sinusoidal waveform has a frequency of half the sampling rate (for example if the sampling
frequency was 100 Hz the duration between samples would be 0.01 seconds. Since there are two
samples per cycle, the period is 0.02 seconds and the frequency is therefore 1/0.02 = 50 Hz). It
can therefore be seen that Nyquist frequency (half the sampling rate) is equivalent to π radians
per sample.
It’s worth noting that in a lot of textbooks and online resources the range of frequencies
along a frequency axis frequently show a range from 0 to π, with units of radians per
sample (rather than a range from 0 to 1 with units of π radians per sample).
Filter types
There are 4 filter types available for the butter function (low-pass, high-pass, band-pass,
and band-stop) and the third input parameter of the butter function specifies the desired
type of filter. You have already seen how to design a low pass filter using [b a] =
butter(1, 0.2,'low'); Now, let’s look at the remaining three filter types.
This code determines the b and a coefficients for a 2nd order high-pass filter with a cutoff-
frequency of 0.55 π radians per sample.
[b a] = butter(2, 0.55,'high');
Digital Filters A practical guide
David Dorran Page 35
This code determines the b and a coefficients for a 5th order band-pass filter with a cutoff-
frequencies of 0.3 π and 0.4 π radians per sample. You’ll notice that the second parameter
passed to the function is a two element array containing the lower cutoff frequency and
the upper cutoff frequency i.e. [0.3 0.4].
[b a] = butter(5, [0.3 0.4],'bandpass');
This code determines the b and a coefficients for a 10th order band-stop filter with a cutoff-
frequencies of 0.6 π and 0.8 π radians per sample. As with the bandpass filter you’ll notice
that the second parameter passed to the function is a two element array containing the
lower cutoff frequency and the upper cutoff frequency i.e. [0.6 0.8].
[b a] = butter(10, [0.6 0.8],'stop');
Digital Filters A practical guide
David Dorran Page 36
Designing a minimum order filter
When engineers are designing filters they often wish to attenuate (reduce) a certain range
of frequencies by a certain amount. They will often also wish to keep another range of
frequencies relatively unchanged. For example, consider a speech processing example
whereby an engineer wishes to reduce high frequency noise above 13 kHz by a factor of
100, in other words attenuate high frequencies by 40 dB. The engineer wants to leave
frequencies below 8 kHz relatively unchanged but can allow for a maximum of a 3 %
reduction in this range of frequencies, since this won’t significantly impact on the speech
quality. The engineer also isn’t too concerned how much frequencies between 8 kHz and
13 kHz are reduced. The engineer is working with speech signals captured at a rate of 32
kHz.
Let’s capture this information in graphical form using a plot, shown below, and introduce
some terminology (see pzdsp.com/vid39 for a related video). The range of frequencies
that are not going to be significantly changed are referred to as the passband. In this
example the passband is from 0 to 8 kHz which equates to a range of 0 to 0.5 π radians
per sample (since the sampling rate is 32 kHz). The amount of change allowed in the
passband (3% in the example) is referred to as the passband ripple and is expressed in
units of dB as the ratio of the input to the output i.e. 20log10(0.97) where the value of 0.97
is obtained from 100% - 3% = 97% = 0.97. So, in this example the passband ripple is 0.2646
dB. The range of frequencies to be attenuated significantly is referred to as the stopband.
In the example the stopband is all frequencies above 13 kHz which equates to a range of
frequencies from 0.8125 π to π radians per sample for a digital filter. The desired reduction
in the stopband is referred to as the stopband attenuation which in this case is 40 dB. The
transition band is the range of frequencies that lie between the passband and the
stopband.
Digital Filters A practical guide
David Dorran Page 37
Filter Design Specification
Passband
0 Hz 8kHz
Passband Ripple permitted
0.2646 dB
Stopband
13 kHz 16kHz
Stopband Attenuation required
40 dB
One way to design a filter to meet this specification is by trial and error. For example,
you might try designing a 4th order filter with a cutoff frequency of 0.6 using the
following code:
>> [b a] = butter(4, 0.6,'low');
You could then examine the frequency response to see if it meets the specification. You
could use the following code to generate plots to use for a visual inspection:
>> H = freqz(b,a);
>> subplot(2,1,1)
>> plot([0:length(H)-1]/length(H), 20*log10(abs(H)))
>> title('Magnitude response of 4th order filter; cutoff
0.6 \pi radians per sample')
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude (dB)');
>> subplot(2,2,3)
>> plot([0:length(H)-1]/length(H), 20*log10(abs(H)))
>> xlim([0 0.5]) %only show the passband
>> title('focus/zoom on passband')
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude (dB)');
Digital Filters A practical guide
David Dorran Page 38
>> subplot(2,2,4)
>> plot([0:length(H)-1]/length(H), 20*log10(abs(H)))
>> xlim([0.8125 1]) %only show the stopband
>> title('focus/zoom on stopband')
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude (dB)');
This first attempt doesn’t meet the specification since all frequency components in the
stopband, above 0.8125 pi radians per sample, are not reduced by at least 40 dB (for
example, at 0.8125 pi radians per sample the attenuation is approximately 35 dB) . Also,
frequency components in the passband, up to 0.5 pi radians per sample, are attenuated by
more than 0.2646 dB, so the filter deign fails to meet the specification in both the
passband and the stopband.
If we went through the same process for an 8th order filter with a cutoff frequency of 0.6
pi radians per sample we’d find that the specification is met (see plots below which could
be obtained by modifying the code above). However, this filter requires significantly more
multiplications and additions to implement and will therefore take more computations
to filter a signal using this filter. A lower order filter that meets the specification would be
preferred.
Digital Filters A practical guide
David Dorran Page 39
There is a built-in function, buttord, that help design a butterworth filter that will meet
the desired specification with the lowest order filter possible. The code below shows how
to use this function. Notice how the function is designed to work with the butter function.
The buttord function takes 4 filter specification parameters as its input (the passband
frequency, stopband frequency, passband ripple and stopband attenuation) and returns
the order and cutoff frequency that must then be used with the butter function, so as to
determine the b and a coefficients of a minimum order filter to meet the filter
specification.
For the example problem given earlier the order (N_min in the code) and cutoff frequency,
(Wc in the code) can be determined using the following line of code:
>> [N_min Wc] = buttord(0.5, 0.8125, 0.2646, 40);
If you run this code you’ll find that the minimum order, N_min, is 6. In order to meet the
specification using this order you would need to set the cutoff frequency to 0.6315 pi
radians per sample i.e. [b a] = butter(6, 0.6315,'low');
Note that if you were to use a different cutoff frequency then the specification would not
be met. For example, if you were to reduce the cutoff frequency to 0.6 then the passband
requirement would not be met. Similarly, if the cutoff frequency was set to 0.7 then the
stopband requirement would not be met. You should try this out for yourself to verify.
Digital Filters A practical guide
David Dorran Page 40
Other filter design functions and their benefits
The butter function is the easiest one to use because it requires the fewest parameters.
There are alternative functions that can achieve a higher roll-off rate for the same order
filter, as discussed in pzdsp.com/vid40. However, these alternatives (Chebyshev and
elliptical design techniques), have what it referred to as “ripple” in the passband and/or
stopband, as shown in the plots below.
Digital Filters A practical guide
David Dorran Page 41
Butterworth filters don’t have “ripple” in either the passband or stopband, and are referred
to as being “maximally flat”. It’s up to the filter designer to determine whether ripple can
be tolerated or not and it really depends on the application (for some applications ripple
might be ok, for others it may not). What’s important to note is that you can achieve a
faster roll-off rate for a lower order filter but it comes at a cost of ripple in the passband
and/or the stopband. The Chebyshev filter rolls-off at a quicker rate than the Butterworth
filter but has ripple in the passband. The elliptical filter rolls-off more quickly than
Chebyshev but has ripple in both the passband and the stopband.
The code used to create the plots above is shown below:
>> [b_butt a_butt] = butter(6, 0.4,'low');
>> [b_cheb a_cheb] = cheby1(6, 2, 0.4,'low');
>> [b_ellip a_ellip] = ellip(6, 2, 20, 0.4,'low');
>> H_butt = freqz(b_butt, a_butt);
>> H_cheb = freqz(b_cheb, a_cheb);
>> H_ellip = freqz(b_ellip, a_ellip);
>>
>> fax = [0:511]/512;
>> subplot(2,1,1)
>> plot(fax, abs(H_butt))
>> hold on
Digital Filters A practical guide
David Dorran Page 42
>> plot(fax, abs(H_cheb))
>> plot(fax, abs(H_ellip))
>> ylabel('Magnitude')
>> xlabel('Frequency ( x \pi radians per sample)')
>> title('Magnitude response comparison - linear
magnitude')
>> legend('Butterworth: No ripple','Chebyshev: Ripple in
passband','Elliptical: Ripple in passband and stopband')
>> subplot(2,1,2)
>> plot(fax, 20*log10(abs(H_butt)))
>> hold on
>> plot(fax, 20*log10(abs(H_cheb)))
>> plot(fax, 20*log10(abs(H_ellip)))
>> ylim([-50 0])
>> ylabel('Magnitude (dB)')
>> xlabel('Frequency ( x \pi radians per sample)')
>> title('Magnitude response comparison in decibels')
>> legend('Butterworth: No ripple','Chebyshev: Ripple in
passband','Elliptical: Ripple in passband and stopband')
The cheby1 function returns a set of b and a coefficients but has four input parameters
(compared with butter’s three). The first parameter specifies the filter order; the third
specifies the cutoff frequency; and the fourth specifies the filter type. The additional
parameter (the second parameter) specifies the maximum ripple allowed in the passband.
The code below plots the frequency response of an 8th order Chebyshev highpass filter
with a cutoff frequency of 0.7π radians per sample, where the maximum allowed passband
ripple is 0.4 dB. You can see in the ‘zoomed in’ passband plot (bottom right) that the ripple
in the passband never exceeds 0.4 dB. Note that higher order filters have more ripple
oscillations.
>> [b a] = cheby1(8, 0.4, 0.7, 'high');
>> H = freqz(b,a);
>> subplot(3,1,1)
>> plot([0:length(H)-1]/length(H), abs(H))
>> title('Magnitude response (linear) of 8^{th} order
Chebyshev high pass filter')
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude');
>> subplot(3,1,2)
>> plot([0:length(H)-1]/length(H), 20*log10(abs(H)))
>> title('Magnitude response (dB) of 8^{th} order
Chebyshev high pass filter')
Digital Filters A practical guide
David Dorran Page 43
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude (dB)');
>> subplot(3,2,6)
>> plot([0:length(H)-1]/length(H), 20*log10(abs(H)))
>> xlim([0.7 1]) %only show the stopband
>> title({'Zoom/focus on passband','0.4dB passband
ripple'})
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude (dB)');
The ellip function returns a set of b and a coefficients but has five input parameters
(compared with butter’s three). The first parameter specifies the filter order; the fourth
specifies the cutoff frequency; and the fifth specifies the filter type. The additional two
Digital Filters A practical guide
David Dorran Page 44
parameters (the second and thirs parameters) specify the maximum ripple allowed in the
passband and the minimum required attenuation in the stopband. The code below plots
the frequency response of a 10th order elliptical bandpass filter with cutoff frequencies of
0.3π and 0.7π radians per sample, where the maximum allowed passband ripple is 3 dB
and the minimum stopband attenuation is 20 dB. You can see in the ‘zoomed in’ passband
plot (bottom left) that the ripple in the passband never exceeds 3 dB, while in the
stopband range of frequencies the ripple is such that it attenuates frequencies by at least
20 dB.
>> [b a] = ellip(10, 3,20, [0.4 0.6], 'bandpass');
>> H = freqz(b,a);
>> subplot(2,1,1)
>> plot([0:length(H)-1]/length(H), 20*log10(abs(H)))
>> title('Magnitude response of 10^{th} order elliptical
bandpass filter')
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude (dB)');
>> subplot(2,3,5)
>> plot([0:length(H)-1]/length(H), 20*log10(abs(H)))
>> xlim([0.401 0.599]) %only show the stopband
>> title({'Zoom/focus on passband'})
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude (dB)');
Digital Filters A practical guide
David Dorran Page 45
Some ‘intuitive’ filters (moving averager, comb filter, DC removal)
The built-in functions (butter, cheby1, ellip) are a convenient way to design a filter,
however the b and a values returned are generally not easy to directly interpret; it’s usually
not possible (or at least its not straightforward) to tell what type of filter you have just by
examining the coefficients directly.
This section presents some filters that are relatively easy to understand directly from the
b and a coefficients, and may provide the reader with some additional insight into how
filters work. This insight is not required in order to design or implement digital filters and
is only provided for the interested reader. Furthermore, if you find this section difficult to
understand you shouldn’t worry about it and skip ahead, it presents a slightly different
perspective that will help some but it may very well hinder others. So, feel free to skip this
section completely if you find it’s not helping!
This section highlights that digital filters operate though a process of constructive and
destructive interference. Certain sinusoidal frequencies will be amplified by constructive
interference, while other frequencies will be reduced though destructive interference.
Moving averager
The difference equation and signal flow diagram for a four-tap moving averager filter are
shown below.
y[n] = 0.25x[n]+0.25x[n-1] +0.25x[n-2] +0.25x[n-3]
This filter takes four consecutive input samples and outputs the average of them. This has
the effect of smoothing out any rapid changes in the signal.
Digital Filters A practical guide
David Dorran Page 46
As an example, a four-tap moving average filter is applied to the following data sequence
which represents the level of a tidal river level, in meters, taken at 20 minute intervals:
[.375 .35 .425 .475 .4 .375 .525 .425 .475 .425 .5 .45 .575 .525 .6 .675 .575 .7 .725 .6]
This raw data is plotted to the left in the figure below and you can see that the readings
fluctuate significantly. The plot to the right shows the result of passing the data through
a four-tap moving average which takes the average over 4 consecutive samples. You see
that the fluctuations in the readings have been smoothed out by the filter.
One way of visualising the moving averager filter in action is to picture a sliding frame of
4 samples being averaged, as shown below, where three filter outputs (shown in green,
blue and red) are calculated by summing the 4 input samples that are contained within
the corresponding coloured frame (e.g. .4187 = 0.25(0.425+0.475+0.4+0.375)).
You should appreciate that the if the number of filter ‘taps’ was reduced from four to two
(the difference equation of such a filter is y[n] = 0.5x[n]+0.5x[n-1]) then the amount of
smoothing would be reduced. Make sure this is clear before proceeding! Similarly
increasing the number of taps would reduce a greater range of high frequencies by a
greater amount i.e. increasing the number of taps reduces fluctuations in the signal by a
greater amount.
The figure below shows the magnitude response of three moving averager filters, and you
can see that they all behave as lowpass filters, since high frequencies are reduced in
amplitude significantly more than low frequencies. You can also see that as the number
Digital Filters A practical guide
David Dorran Page 47
of ‘taps’ increases that the higher frequencies are reduced by a greater amount, as you
would expect.
>> fax = [0:511]/512;
>> a = 1;
>> b = [0.5 0.5]; % 2-tap moving averager
>> H = freqz(b,a);
>> plot(fax, abs(H))
>> hold on
>> b = [0.25 0.25 0.25 0.25]; % 4-tap moving averager
>> H = freqz(b,a);
>> plot(fax, abs(H))
>> b = [0.125 0.125 0.125 0.125 0.125 0.125 0.125 0.125];
% 8-tap
>> H = freqz(b,a);
>> plot(fax, abs(H))
>> legend('2-tap', '4-tap', '8-tap')
>> title('Magnitude response of 3 Moving Averager
filters')
>> xlabel('Frequency (x \pi radians per sample');
>> ylabel('Magnitude')
You’ll also notice that certain frequencies are reduced to zero. For example, the 4-tap
moving averager attenuates frequencies of π/2 radians per sample to zero. The reason for
these zeros (or nulls) in the magnitude response can, perhaps, be more easily understood
by visualising the filters behaviour in slightly different way.
Digital Filters A practical guide
David Dorran Page 48
An equally valid way of depicting a four-tap moving averager is to explicitly show the
output as a sum of delayed inputs, as shown below. You should compare this with the
signal flow diagram shown earlier.
Let’s use some plots to reinforce this way of thinking about the four-tap moving averager.
Notice that x[n-1] is the same as x[n] but with a zero sample placed at the beginning of the
signal. Similarly, x[n-2] is the same as x[n] but with two zero samples placed at the
beginning of the signal. Prepending a signal with d zeros introduces a delay of d into the
signal. For example, the sample values in the signal x[n-2] shown in the plot contains the
same values as x[n] 2 samples previously.
x[n]y[n]
x[n-
1
]
x[n-
2
]
x[n-
3
]
x[n]
y[n]
x[n-
1
]
x[n-
2
]
x[n-
3
]
4y[n]
Digital Filters A practical guide
David Dorran Page 49
The code below also shows the equivalence of this view compared with the usual way of
filtering using an example. In the code the filter output is determined in two different
ways but the result is the same.
>> x = [.375 .35 .425 .475 .4 .375 .525 .425 .475 .425 .5
.45 .575 .525 .6 .675 .575 .7 .725 .6 ];
>> x_delayed_1 = [ 0 .375 .35 .425 .475 .4 .375 .525 .425
.475 .425 .5 .45 .575 .525 .6 .675 .575 .7 .725 ];
>> x_delayed_2 = [ 0 0 .375 .35 .425 .475 .4 .375 .525
.425 .475 .425 .5 .45 .575 .525 .6 .675 .575 .7 ];
>> x_delayed_3 = [ 0 0 0 .375 .35 .425 .475 .4 .375 .525
.425 .475 .425 .5 .45 .575 .525 .6 .675 .575 ];
>>
>> b = [0.25 0.25 0.25 0.25];
>> a = 1;
>> y = filter(b, a, x);
>> n = 0:length(y)-1;
>> y2 = 0.25*x + 0.25*x_delayed_1 + 0.25*x_delayed_2 +
0.25*x_delayed_3;
>> plot(n, y)
>> hold on
>> plot(n, y2, 'r.', 'MarkerSize',10)
>> xlabel('Samples')
>> ylabel('Amplitude')
>> legend('Conventional filter output','Alternative filter
output');
To appreciate why there are zeros (or nulls) in the magnitude spectrum at certain
frequencies let’s take a look at how the four-tap moving averager processes sinusoidal
waveforms. The figure below shows a sinusoidal waveform of frequency 0.5π radians per
sample as the input. Notice how the peaks of the input x[n] and the troughs of x[n-2] are
aligned vertically i.e. for the samples when x[n] is 1 the signal x[n-2] is -1. Therefore, the
0 2 4 6 8 10 12 14 16 18 20
Samples
0
0.2
0.4
0.6
0.8
Am plitude
Conventional filter output
Alternative f ilter output
Digital Filters A practical guide
David Dorran Page 50
sum of x[n] and x[n-2] is 0 for all samples. Similarly, the sum of x[n-1] and x[n-3] will be
0, for all samples. It follows that the sum of x[n] , x[n-1], x[n-2] and x[n-3] will also be zero,
as shown below.
For lower frequency sinusoidal waveforms the peaks and troughs of the sinusoidal input
and delayed versions of the input will not be aligned and, therefore, cannot sum to zero,
as shown in the plot below.
x[n]
y[n]
x[n-
1
]
x[n-
2
]
x[n-
3
]
4y[n]
x[n]
y[n]
x[n-
1
]
x[n-
2
]
x[n-
3
]
4y[n]
Digital Filters A practical guide
David Dorran Page 51
If you fully appreciate the above analysis then you should be able to predict the
frequencies at which nulls will occur for moving averagers with any number of taps. In
general, nulls will occur at frequencies of k2π/p, where p is the number of taps and k is an
integer; try to make sure you appreciate why this is the case before moving on.
Comb filter
The frequency response of a comb filter resembles the shape of a hair comb, and it
attenuates certain (equally spaced) frequencies significantly.
It’s a straightforward filter to implement since it just the sum of the input and delayed
and inverted version of the input, as depicted in the figure below. If the input isn’t inverted
(multiplied by -1) then the frequency response is similar but the nulls of the frequency
response occur at different locations.
Nulls occur in the frequency response for the same reason as nulls occur in a moving
averager filter i.e. certain sinusoidal waveforms will destructively interfere when summed.
Where the nulls occur depend upon the length of the delay. If the delayed input is inverted
prior to summing then nulls will occur at k2π/d radians per sample, where d is the delay
Digital Filters A practical guide
David Dorran Page 52
and k is an integer. Let’s take a look at this ‘null phenomenon’ for a comb filter with a
delay of 6 samples.
A signal flow diagram of the comb filter with a delay of 6 samples can be shown in a
number of equivalent ways, as shown in the three examples below.
The top-left signal flow diagram most closely matches how Octave and Matlab filter
signals, since it explicitly shows the b1, b2, b3, b4 and b5 coefficients as being zero (see code
below). However, the signal flow diagram at the bottom is perhaps the most intuitive in
terms of appreciating why the nulls occur at certain frequencies.
>> b = [1 0 0 0 0 0 -1];%[b0 b1 b2 b3 b4 b5 b6]
>> a = 1;
>> H = freqz(b,a);
>> fax = [0:length(H)-1]/length(H);
>> plot(fax,abs(H))
x[n]
x[n-6]
y[n]
x[n]y[n]
x[n]y[n]
Digital Filters A practical guide
David Dorran Page 53
>> xlabel('Frequency (x \pi rads/sample)')
>> ylabel('Magnitude')
>> title('Magnitude response of Comb Filter with delay of
6 samples')
Referring to the plots below, you should appreciate that both the π/3 and the 2π/3 radians
per sample sinusoidal waveforms will ‘repeat’ every 6 samples. It therefore follows that if
either waveform was to be delayed by 6 samples and inverted that it would destructively
interfere with the original waveform. A similar thought process can be used to explain the
nulls for other delay lengths.
DC removal (a basic high pass filter)
A very basic highpass filter is given by the following difference equation.
y[n] = x[n]-x[n-1]
Digital Filters A practical guide
David Dorran Page 54
This filter removes constant amplitude components (known as DC components) from a
signal. If the amplitude of a signal remains constant then the output of this simple
highpass filter will be zero, since the output equals the current sample minus the previous
sample, and the current sample equals the previous sample for signals in which the
amplitude is a constant.
If the input signal to this filter contains a DC offset (i.e. the signal does not oscillate
around zero) the DC offset will be removed, as shown in the code and plot below. Notice
that the phase of the sinusoidal component has been changed and that there is also a
slight change in amplitude. Notice also that the output oscillates around 0 i.e. it has no
DC offset.
>> N = 20;
>> n = 0:N-1;
>> b = [1 -1];
>> a = 1;
>> x = cos(pi/3*n)+1;
>> y = filter(b,a, x);
>> plot(n,x)
>> hold on
>> plot(n,y)
>> legend('Input Signal','Output Signal')
0 2 4 6 8 10 12 14 16 18
Samples
-1
-0.5
0
0.5
1
1.5
2
Amplitude
Input Signal
Output Signal
Digital Filters A practical guide
David Dorran Page 55
>> xlabel('Samples')
>> ylabel('Amplitude')
This filter also basically just a comb filter with a delay of just one sample, and it follows
the same ‘comb filter rulethat nulls will occur at k2π/d radians per sample, where d is the
delay, which is 1 for this filter. Therefore nulls will occur at 0, 2π , 4π, 6π, ... radians per
sample. Over the range of Nyquist frequencies there is therefore only a single null at 0
radians per sample, as shown in the frequency response below.
Linear Time-Invariant (LTI) systems
The discrete systems used in this series of documents are both Linear and Time-Invariant,
which means that they behave in a very predictable manner. The following subsections
briefly describe some properties of LTI systems and provide coded demonstrations
verifying discrete systems are Linear and Time Invariant. This section isn’t highly
important and can be skipped without significant impact and is just included here for the
sake of completeness.
Linearity
Linear systems respond proportionally to any given input, so if an input g[n] produces an
output s[n] then an input 3.g[n] produces an output 3.s[n].
Digital Filters A practical guide
David Dorran Page 56
Let’s demonstrate that discrete systems exhibit this scaling property using a coded
example.
>> g = randn(1,40);
>> g_by_3 = 3*g;
>>
>> b = [0.5 0.5];
>> a = [1 -1.3025 0.49];
>> s = filter(b,a,g);
>> s2 = filter(b,a,g_by_3);
>> s_by_3 = 3*s;
>>
>> plot(s2, 'Linewidth', 12)
>> hold on
>> plot(s_by_3,'Linewidth', 3)
>> ylabel('Amplitude')
>> xlabel('Samples')
>> legend('Filter output when original input is scaled by
3', 'Output of unscaled original output scaled by 3')
IF
THEN
for any scalar
k
g[n]Linear
Sy st e m s[n]
k.g[n]Linear
Sy st e m k.s[n]
Scal ing Property of Linear Systems
Digital Filters A practical guide
David Dorran Page 57
Another property of a linear system is the ‘summing property’, which dictates that if an
input signal g[n] produces an output s[n], and a different input signal m[n] produces an
output c[n]; then an input of g[n]+m[n] will produce an output s[n]+c[n].
Let’s demonstrate that discrete systems exhibit this summing property using a coded
example.
>> g = randn(1,40);
>> m = randn(1,40);
>> m_plus_g = g+m;
>>
>> b = [0.5 0.5];
>> a = [1 -1.3025 0.49];
>> s = filter(b,a,g);
>> c = filter(b,a,m);
>> y = filter(b,a,m_plus_g);
>> s_plus_c = s+c;
>>
>> plot(y, 'Linewidth', 12)
>> hold on
>> plot(s_plus_c,'Linewidth', 3)
>> ylabel('Amplitude')
>> xlabel('Samples')
>> legend('Filter output when input is g+m', 'Sum of s and
c')
0510 15 20 25 30 35 40
Samples
-20
-10
0
10
20
Amplitude
Filter output w hen original input is sc aled by 3
Output of uns caled original output sc aled by 3
Digital Filters A practical guide
David Dorran Page 58
Time-Invariance
Time invariant systems behave in the same way when you apply the same input at a
different time. A lot of systems behave like this for example if I applied a particular
voltage to an electrical circuit at 10:00am I’d expect to see the same output if I applied the
same input voltage to the circuit at 4:00pm. Similarly, if dropped a football, from a height
0510 15 20 25 30 35 40
Samples
-6
-4
-2
0
2
4
6
Amplitude
Filter output w hen input is g+m
Sum of s and c
IF
THEN
g[n]Linear
Sy st e m s[n]
g[n]+m[n]Linear
Sy st e m s[n]+c[n]
A ND
m[n]Linear
Sy st e m c[n]
Summing Property of Linear Systems
Digital Filters A practical guide
David Dorran Page 59
of 1 meter, on my kitchen floor at 9:00 am and then again at 9:30 am then the ball would
bounce in the same manner.
The code below demonstrates that discrete systems exhibit this time-invariance property.
There are two inputs which have the same time-domain shape/samples but one input is a
delayed version of the other.
>> seg = randn(1,40);
>> p = 20; %the delay
>> g = [seg zeros(1,40)];
>> w = [ zeros(1,p) seg zeros(1,40-p)];
>>
>> b = [0.5 0.5];
>> a = [1 -1.3025 0.49];
>> s = filter(b,a,g);
>> y = filter(b,a,w);
>> s_delayed = [zeros(1,p) s(1:end-p)];
>>
>> plot(y, 'Linewidth', 12)
>> hold on
>> plot(s_delayed,'Linewidth', 3)
>> ylabel('Amplitude')
>> xlabel('Samples')
>> legend('Filter output when input is w[n]=g[n-20]',
's[n-20]')
If a signal w[n] is a delayed version of g[n], where the delay is p samples then w[n] = g[n-
p]. It can be useful to verify this using an example. Let’s make g[n] be the sequence [3 5 -6
1] and w[n] be the sequence [0 0 0 3 5 -6 1] i.e. they are the same shape/samples but have
a delay of 3 samples between them. Now lets show that w[n] = g[n-p] when the delay p is
3, by evaluating the equation for different values of n.
010 20 30 40 50 60 70 80
Samples
-6
-4
-2
0
2
4
Amplitude
Filter output w hen input is w [n]=g[n-20]
s[n-20]
Digital Filters A practical guide
David Dorran Page 60
when n = 0, w[0] = g[-3] = 0
when n = 1, w[1] = g[-2] = 0
when n = 2, w[2] = g[-1] = 0
when n = 3, w[3] = g[0] = 3
when n = 4, w[4] = g[1] = 5
when n = 5, w[5] = g[2] = -6
when n = 6, w[6] = g[3] = 1
We can therefore summarise the time-invariance property of discrete systems as follows.
Transient response of filters
The transient response of a system refers to how the system reacts to a ‘sudden’ change to
the input signal characteristics. An example of this is shown below, whereby the input
signal (top plot) suddenly changes from a long sequence of zeros to a long sequence of
ones. This input signal is applied to the system shown below and given by the difference
equation, with the corresponding signal flow diagram also provided:
y[n] = x[n]+1.7773y[n-1]-0.8464y[n-2]
IF
THEN
for any delay
p
g[n]
T ime
Invariant
Sy st e m
s[n]
g[n-p]s[n-p]
T ime
Invariant
Sy st e m
Property of Time-Invariant Systems
Digital Filters A practical guide
David Dorran Page 61
Before the sudden ‘step change’ in the input, from zero to one (at sample number 130),
the output (and the system) is said to be in steady state i.e., the output signals
characteristics are not changing significantly (while, over the same samples, the input
characteristics are also not changing significantly). The system (and the output) re-enters
steady state at approximately sample number 200, and for the range of samples between
130 and 190 the output is in a transient state for approximately 60 samples.
Shown below is a second example, using the same system, whereby there are two transient
states and three steady states in the output. In this example, the input is a sequence of
zeros concatenated with a sinusoidal waveform segment of frequency π/12 radians per
sample and a second sinusoidal waveform segment of frequency π/24 radians per sample.
50 100 150 200 250
Samples
0
0.5
1
Amplitude
System Input
50 100 150 200 250
Samples
0
10
20
Amplitude
System Output/Response
Steady State Steady State
Transient State
Digital Filters A practical guide
David Dorran Page 62
When a system is in steady state a sinusoidal segment, having a constant amplitude, at
the input will have a constant amplitude over the same range of samples at the output.
This is generally not the case during a transient state. For example, if you examine the
output signal in the above plot over the range of samples from 130 to 190 (the pink
transient region) you will see that the amplitude of the oscillating signal is changing, while
the inputs oscillation amplitude is constant, over the same range of samples.
You’ll also notice that you will have the same oscillation frequency at the input and
output, over the same range of samples, during steady state. This is generally not the case
during a transient state. Notice how the frequency of oscillation during the transient state,
between samples 380 and 440, is not constant.
The code below can be used to generate the plots above and the reader is encouraged to
experiment with this code to develop their understanding of a systems transient response.
Note that the duration of the transient regions is dependent upon the system’s difference
equation and that for some systems the transient response can be very short. For example,
a system given by y[n] = 0.5x[n]+0.5x[n-1] will have transient regions that are only one
sample long.
>> f1 = pi/12; % pi/12 radians per sample
100 200 300 400 500 600
Samples
-1
0
1
Amplitude
System Input
100 200 300 400 500 600
Samples
-20
0
20
Amplitude
System Output/Response
Steady State
Steady State
Steady State
Transient State Transient State
Digital Filters A practical guide
David Dorran Page 63
>> f2 = pi/24; % pi/24 radians per sample
>>
>> b = 1;
>> a = [1.0000 -1.7773 0.8464];
>>
>> N = 260;
>> n = 0:N-1;
>>
>> x = [zeros(1, N/2) cos(n*f1) cos(n*f2)];
>> % uncomment the following line for the first example
>> % x = [zeros(1, N/2) ones(1, N/2)];
>>
>> y = filter(b,a,x);
>> subplot(2,1,1)
>> plot(x)
>> xlabel('Samples')
>> ylabel('Amplitude')
>> title('System Input')
>> subplot(2,1,2)
>> plot(y)
>> title('System Output/Response')
>> xlabel('Samples')
>> ylabel('Amplitude')
Why transients always occur at system start-up
Whenever you apply a signal to a discrete system you will find that the system behaves as
if a sequence of zeros were prepended to the input signal. For example, if were just to
apply a sequence of ones to the example system used earlier you would get the following
plot. Notice how the first 60 output samples are the same as the transient region in the
earlier plot, and that the output reaches steady state after the transient state.
Digital Filters A practical guide
David Dorran Page 64
To appreciate why this happens let’s consider a more simple system and consider the case
where the input to the system below is a value of zero followed by a sequence of ones i.e.
x[n] = [0, 1 , 1, 1 ,1 ,1 ,1 , 1, 1 ….], so x [0] = 0, x[1] = 1, x[2] = 1 , x[3] = 1, etc.
y[n] = 0.25x[n]+0.25x[n-1] +0.25x[n-2] +0.25x[n-3]
To determine the output we can evaluate the difference equation for different values of n.
For n = 0 the difference equation becomes:
y[0] = 0.25x[0]+0.25x[-1] +0.25x[-2] +0.25x[-3]
While x[0] is explicitly defined to be 0 above x[-1], x[-2] and x[-3] are not explicitly defined,
and when samples are not explicitly defined they are assumed to be zero. We can then
evaluate y[0] as follows.
020 40 60 80 100 120 140
Samples
0
1
2
Am plitude
Syste m Input (seque nce of ones)
020 40 60 80 100 120 140
Samples
0
10
20
Am plitude
Syste m Output/Res ponse
Digital Filters A practical guide
David Dorran Page 65
y[0] = 0.25(0)+0.25(0) +0.25(0) +0.25(0) = 0
Similarly, we could evaluate the next 4 output samples as follows:
y[1] = 0.25x[1]+0.25x[0] +0.25x[-1] +0.25x[-2]
= 0.25(1)+0.25(0) +0.25(0) +0.25(0) = 0.25
y[2] = 0.25x[2]+0.25x[1] +0.25x[0] +0.25x[-1]
= 0.25(1)+0.25(1) +0.25(0) +0.25(0) = 0.5
y[3] = 0.25x[3]+0.25x[2] +0.25x[1] +0.25x[0]
= 0.25(1)+0.25(1) +0.25(1) +0.25(0) = 0.75
y[4] = 0.25x[4]+0.25x[3] +0.25x[2] +0.25x[1]
= 0.25(1)+0.25(1) +0.25(1) +0.25(1) = 1
You should appreciate that all subsequent output samples will be a value of 1 i.e. y[5] = 1,
y[6] = 1, y[7] = 1, etc.
You should also appreciate that if the input is a sequence of ones then the output would
be very similar i.e. y[0] = 0.25, y[1] = 0.5 , y[2] = 0.75, y[3] = 1, y[4] = 1 , y[5] = 1, etc.
In this example system, the transient response to a sudden ‘step’ change is 3 samples in
duration. This transient will always occur at system start-up because in order to determine
the system output for the first 3 samples you have to assume that the previous input
samples are zero in order to evaluate the difference equation (as shown in the calculations
above). So, at start-up the system therefore behaves as if the input signal was prepended
with a sequence of zeros.
Digital Filters A practical guide
David Dorran Page 66
For systems that only rely on past outputs, like the one used at the beginning of this
section (given by the difference equation y[n] = x[n]+1.7773y[n-1]-0.8464y[n-2]), a similar
situation occurs, except in this case the initial past output samples, i.e. y[-1] and y[-2], are
assumed to be zero when evaluating the difference equation for the first 2 output samples.
The effects of this assumption propagates through the system output for another 60
samples since these output samples are being fed back into the system.
12345678910
Samples
0
0.5
1
Amplitude
Syste m Input
1 2 3 4 5 6 7 8 9 10
Samples
0
0.5
1
Amplitude
Syste m Out put/Response
Steady State
Transient State
0
0
ResearchGate has not been able to resolve any citations for this publication.
ResearchGate has not been able to resolve any references for this publication.