DSP 394

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

PRACTICAL WORK BOOK

Digital Signal Processing


(EE-394/EE-493)

Name:

Roll Number:

Class: Section:

Batch: Semester:

Department :

Department of Electrical Engineering


N.E.D. University of Engineering & Technology, Karachi
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

CONTENTS

Lab.
Title of Experiments Dated Remarks
No.

1 Effects of Sampling in Discrete Time Signals.

Effects of Quantization in Discrete Time Continuous Valued


2 Signals.

3 Discrete-Time Convolution.

4 Discrete-Time Correlation.

5 Effects of Re-Sampling in Discrete Time Signals.

6 The Discrete Fourier Transform as a Linear Transformation

Studying Discrete Fourier Transform using an audio signal


7 example.

8 Relationship between Laplace and CTFT.

9 Relationship between Z transform and DTFT.

10 Designing FIR filters with windowing

11 Designing IIR filters using fdatool


Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 01
Effects of Sampling in Discrete Time Signals

OBJECTIVE:

To study the relationship between discrete-time and continuous time signals by examining
sampling and aliasing.

THEORY:

Signals are physical quantities that carry information in their patterns of variation. Continuous-
time signals are continuous functions of time, while discrete-time signals are sequences of
numbers. If the values of a sequence are chosen from a finite set of numbers, the sequence is
known as a digital signal. Continuous-time, continuous-amplitude signals are also known as
analog signals.

Analog phenomenon is continuous – like a human speech of speaker, or a continuously rotating


disc attached to the shaft of motor etc. With analog phenomena, there is no clear separation
between one point and the next; in fact, between any two points, an infinite number of other
points exist. Discrete phenomenon, on the other hand, is clearly separated. There's a point (in
time or space), and then there's a neighboring point, and there's nothing between the two.

Signal processing is concerned with the acquisition, representation, manipulation,


transformation, and extraction of information from signals. In analog signal processing these
operations are implemented using analog electronic circuits. Converting the continuous
phenomena of images, sound, and motion into a discrete representation that can be handled by a
computer is called analog-to-digital conversion. Digital signal processing involves the
conversion of analog signals into digital, processing the obtained sequence of finite precision
numbers using a digital signal processor or general purpose computer, and, if necessary,
converting the resulting sequence back into analog form. When stored in a digital computer, the
numbers are held in memory locations, so they would be indexed by memory address.
Regardless of the medium (either sound or an image), analog-to-digital conversion requires the
same two steps: Sampling and Quantization.
Sampling: This operation chooses discrete (finite) points at which to measure a continuous
phenomenon (which we will also call a signal). In the case of sound, the sample points are
evenly separated in time. In the case of images, the sample points are evenly separated in space.
Sampling Rate: The number of samples taken per unit time or unit space is called the sampling
rate. The frequency of sampled/discrete phenomenon (signal) can be calculated as
fd = F /Fs (cycles/sec )/(samples/sec) = cycles/ samples
Where, F = Frequency of analog or continuous phenomenon (signal). [Unit: cycles/sec]
Fs = Sampling frequency or sampling rate [Unit: samples/sec]
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

fd = Frequency of Discrete phenomenon (signal). [Unit: cycles/sample]

Sampling Theorem: A continuous time phenomenon or signal like x(t) can be reconstructed
exactly from its samples x(n) = x(nTs), if the samples are taken at a rate Fs = 1/Ts
that is greater than twice the frequency of the signal being sampled i.e. Fs ≥ 2 ∗ F.

Mathematically,

Aliasing: A common problem that arises when sampling a continuous signal is aliasing, where a
sampled signal has replications of its sinusoidal components which can interfere with other
components. It is an effect that causes two discrete time signals to become indistinct due to
improper sampling (fd>1/2 cycles/sample).

PROCEDURE:

1. Simulate and plot two CT signals of 10 Hz and 110 Hz for 0 < t < 0.2 secs.
2. Sample at Fs = 100 Hz and plot them in discrete form.
3. Observe and note the aliasing effects.
4. Explore and learn.
STEPS:
1. Make a folder at desktop and name it as your current directory within MATLAB.
2. Open M-file editor and type the following code:
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

clear all;close all;clc;

F1 = 10;
F2 = 110;
Fs = 100;
Ts = 1/Fs;
t = [0 : 0.0005 : 0.2];
x1t = cos(2*pi*F1*t);
x2t = cos(2*pi*F2*t);

figure,
plot(t,x1t,t,x2t, 'LineWidth',2);
xlabel('cont time (sec)');
ylabel('Amp');
xlim([0 0.1]);
grid on;
legend('10Hz','110Hz');
title('Two CTCV sinusoids plotted');

3. Save the file as P011.m in your current directory and ‘run’ it, either using F5 key or
writing
the file name at the command window.
(Check for the correctness of the time periods of both sinusoids.)

Now add the following bit of code at the bottom of your P011.m file and save.

nTs = [0 :Ts : 0.2];


n = [1 : length(nTs)-1 ];

x1n = cos(2*pi*F1*nTs);
x2n = cos(2*pi*F2*nTs);

figure,
subplot(2,1,1),
stem(nTs,x1n,'LineWidth',2);
grid on;
xlabel('discrete time (sec)');
ylabel('Amp');
xlim([0 0.1]);

subplot(2,1,2)
stem(nTs,x2n,'LineWidth',2);
grid on;
title('110Hz sampled')
xlabel('discrete time(sec)');
ylabel('Amp');
xlim([0 0.1]);
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

1. Before hitting the ‘run’, just try to understand what the code is doing and try to link it
with what we have studied in classes regarding concepts of frequency for DT signals.
2. Now ‘run’ the file and observe both plots.

To see what is really happening, type the following code at the bottom of your existing
P011.m file and run again.

figure,
plot(t,x1t,t,x2t);
hold;
stem(nTs,x1n,'r','LineWidth',2);

xlabel('time (sec)');
ylabel('Amp');
xlim([0 0.05]);

legend('10Hz','110Hz');

3. Observe the plots.

RESULT:

Explain (write) in your own words the cause and effects of what you just saw.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB TASKS:

1. Consider the following CT signal:


x(t) = sin (2 pi F0 t). The sampled version will be:
x(n) = sin (2 pi F0/Fs n),
where n is a set of integers and sampling interval Ts=1/Fs.
Plot the signal x(n) for n = 0 to 99
for Fs = 5 kHz and F1 = 0.5, 2, 3 and 4.5 kHz. Explain the similarities and differences among
various plots.

2. Generate a tone in MATLAB with varying frequency f = 1000,2000,3000,4000, 5000, 6000,


8000, 9000, 25000,-1000,-2000,-3000 Hz with Fs = 8000 samples/sec.
Listen to the tones,and observe at Sounds like what frequency?
Also Specify whether Aliasing is happening or not.

3. Record a sentence in your voice.(you may use Simulink /audacity to record).Change Fs


=44100, 22050, 11025, 8192, 4096 , 2048 , 1024
and observe

a) Voice quality during playback [Excellent/Good/OK/Bad]


b) File size in kilobytes
c) Aliasing happening or not?
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 02
Effects of Quantization in Discrete Time Continuous Valued Signals

OBJECTIVE:

To observe the quantization effects on sampled signals and to understand how quantization leads
to quantization error. In this lab, we will investigate the influence of the number of quantization
levels on the quality of digitized signal. Method of selection of ADC is also a part of this lab
session.

THEORY:
Everything stored on a computer is discrete time discrete valued signal. Because computer has
finite number of registers and each register is a finite length register. We take too many samples
to give the ‘effect’ of continuous time signals. But actually they are discrete time. We also take
very fine resolution of amplitude axis to give the effect of continuous valued signal but due to
finite word length of the computer register, the stored variables are already quantized. This lab
aims to explain the quantization effects in a computer.

Regardless of the medium (audio or image), the digitization of real world analog signal
usually involves two stages: sampling, i.e. the measurement of signal at discretely spaced
time intervals, and quantization, i.e. the transformation of the measurements (amplitudes)
into finite-precision numbers (allowed discrete levels), such that they can be represented in
computer memory. Quantization is a matter of representing the amplitude of individual
samples as integers expressed in binary. The fact that integers are used forces the samples to
be measured in a finite number of bits (discrete levels). The range of the integers possible is
determined by the bit depth, the number of bits used per sample. The bit depth limits the
precision with which each sample can be represented.

Bit Depth:

Within digital hardware, numbers are represented by binary digits known as bits—in fact, the
term bit originated from the words Binary digit. A single bit can be in only one of two possible
states: either a one or a zero. When samples are taken, the amplitude at that moment in time
must be converted to integers in binary representation. The number of bits used to represent
each sample, called the bit depth (bits/sample) or sample size, determines the precision with
which the sample amplitudes can be represented. Each bit in a binary number holds either a 1 or
a 0. In digital sound, bit depth affects how much you have to round off the amplitude of the
wave when it is sampled at various points in time
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

The number of different values that can be represented with b-bit is 2b .The largest decimal
number that can be represented with an b-bit binary number is 2 b - 1. For example, the
decimal values that can be represented with an 8-bit binary number range from 0 to 255, so
there are 256 different values (levels of ADC). A bit depth of 8 allows 2 8=256 different
discrete levels at which samples can be approximated or recorded. Eight bits together
constitute one byte. A bit depth of 16 allows 2 16 = 65,536 discrete levels, which in turn
provides much higher precision than a bit depth of 8.

The number of bits in a data word is a key consideration. The more bits used in the word, the
better the resolution of the number, and the larger the maximum value that can be represented.
Some computers use 64-bit words. Now, 264 is approximately equal to 1.8 x 1019—that's a pretty
large number. So large, in fact, that if we started incrementing a 64-bit counter once per second
at the beginning of the universe (≈20 billion years ago), the most significant four bits of this
counter would still be all zeros today.
To simplify the explanation, take an example of ADC with a bit depth of 3, 2 3 = 8
quantization levels ranging from -4 to 3 are possible in signed magnitude representation. For
bipolar ADCs (or signed magnitude representation), by convention, half of the quantization
levels are below the horizontal axis (that is 21, of the quantization levels). One level is the
horizontal axis itself (level 0), and 2b-1 − 1levels are above the horizontal axis.Note that since
one bit is used for the signed bit (in 2-complementformat), the largest magnitude corresponds
to 2^(b -1 ). (not 2b). When a sound is sampled, each sample must be scaled to one of the
8 discrete levels. However, the samples in reality might not fall neatly onto these levels. They
have to be rounded up or down by some consistent convention.

QUANTIZATION ERROR:

The samples, which are taken at evenly-spaced points in time, can take on the values only
at the discrete quantization levels to store on our computer. Therefore quantization leads
to a loss in the signal quality, because it introduces a “Quantization error”.
Quantization error is sometimes referred to as '"Quantization noise". Noise can be
broadly defined as part of an audio signal that isn’t supposed to be there. However, some
sources would argue that a better term for quantization error is "distortion", defining
distortion as an unwanted part of an audio signal that is related to the true signal.
The difference between the quantized samples and the original samples constitutes
quantization error or rounding error (if round-off method is used). Xe(n) = Xq(n) − x(n).
The lower the bit depth, the more values potentially must be approximated (rounded),
resulting in greater quantization error

To calculate the required bit depth of ADC i.e. bits/sample, there are two
important points which we must have to consider:
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

a) How much noise is already present in the analog signal?


b) How much more noise can be tolerated in the digital
signal? Signal-to -noise-ratio- SNR (of analog signal)
Before looking at SNR specifically in the context of digital imaging and sound, let's
consider the general definition. Signal-to-noise ratio can generally be defined as the ratio
of the meaningful content of a signal versus the associated background noise.

SNR = 10log10 (Px /Pe )


Where, Pxand Pe are average power of the analog signal and noise signal
respectively.
A signal is any type of communication – something a person says to you, a digital
signal sending an image file across a network, a message posted on an electronic
bulletin board, a piece of audio being played from a cassette, etc. The noise is the
part of the message that is not meaningful; in fact, it gets in the way of the
message intended in the communication. You could use the term signal-to-noise
ratio to describe communications in your everyday life. If you know someone who
talks a lot but doesn't really convey a lot of meaning, you could say that he or she
has a low signal-to-noise ratio. Web-based bulletin board and chat groups are
sometimes described as having a low SNR – there may be quite a few postings,
but very much meaningful content. In these first two examples, the noise consists
of all the empty "filler" words. In the case of a digital signal sent across a
network, the noise is the electronic degradation of the signal. On a piece of audio
played from cassette, the noise could be caused by damage to the tape or
mechanical imperfections in the cassette player.
In analog data communication (analog signals), the signal-to-noise ratio is
defined as the ratio of the average power in the signal versus the power in the
noise level. In this context, think of a signal being sent over a network
connection compared to the extent to which the signal is corrupted. This is
related to the general usage of the term described above. This usage of the term
SNR applies to analog signals.
SIGNAL-TO-QUANTIZATION-NOISE-RATIO- SQNR (OF ADC):
Using finite word lengths prevents us from representing values with infinite precision, increases
the background noise in our spectral estimation techniques etc. The amount of error implicit in a
chosen bit depth can be measured in terms of the signal-to-noise ratio (SNR).
For a digitized image or sound, the signal-to-noise ratio is defined as the ratio of the
maximum sample value versus the maximum quantization error. In this usage of the term ,
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

the ratio depends on the bit depth chosen for the signal. Any signal encoded with a given bit
depth will have the same ratio. This can also be called signal-toquantization-noise ratio
(SQNR), but you should be aware that in many sources the term signal-to-noise ratio is used
with this meaning as well. (Henceforth, we'll use the term SQNR to distinguish this
measurement from SNR.)
Practical A/D converters are constrained to have binary output words of finite length.
Commercial A/D converters are categorized by their output word lengths, which are
normally in the range from 8 to 16 bits. There is no infinite bit ADC. So whenever we will
digitize our signal, we will always have a quantization error. Quantization error represen ts
the quality of quantization process but the total error may also turn out to be zero, so signal -
toquantization-noise-ratio (SQNR) is used to describe the quality of quantization process
and it can be defined as

SQNRA/D = 10 log 10(Px /Pe)


Where, Px~and Pe are average power of the DTCV (sampled) signal and quantization error
signal respectively.

PROCEDURE:

1. Simulate a DTCV sinusoid of 1/50 cycles/sample with length of the signal be 500.
2. Choose the no. of significant digits for round-off and apply to the signal generated above.
3. Compute the error signals and SQNR
4. Explore and observe.

STEPS:

1. Make a folder at desktop and name it as your current directory within MATLAB.
2. Open M-file editor and write the following code:

clear all;
close all;
clc;
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

fd1 = 1/50;
n = [0 : 499 ];

q=input('No. of Digits after decimal points to be retained (0-9): ');


x1 = cos(2*pi*fd1*n);
Px1 = sum(abs(x1).^2)/length(x1);
x1q = round(x1*10^q)/10^q;
x1e = x1 -x1q;
Pe1 = sum(abs(x1e).^2)/length(x1e);

SQNR = 10*log10(Px1/Pe1);
disp(['The Signal to Quantization Noise Ratio is: ' num2str(SQNR) '
dB.' ]);
figure,
subplot(2,1,1);
plot(n,x1,n,x1q);
xlabel('indices');
ylabel('Amp');
xlim([0 49]);
ylim([-1.1 1.1]);
legend('DTCV','DTDV');

subplot(2,1,2);
plot(n,x1e);
xlabel('indices');
ylabel('Error');
xlim([0 49]);

3. Save the file as P021.m in your current directory and run it.

Explore and take notes.


Now modify the above code as follows and save as another file P022.m.

clear all;
close all;
clc;
fd1 = 1/50;
n = [0 : 499 ];
q = [0 : 10];

% No. of Digits after decimal points to be retained for num = 1 :


length(q)
x1 = cos(2*pi*fd1*n);
Px1 = sum(abs(x1).^2)/length(x1);
x1q = round(x1*10^q(num))/10^q(num);
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

x1e = x1 -x1q;
Pe1 = sum(abs(x1e).^2)/length(x1e);
SQNR(num) = 10*log10(Px1/Pe1);
end

figure,
plot(q,SQNR);
xlabel('Significant Digits');
ylabel('SQNR (dB)');
xlim([q(1) q(end)]);

1. Before hitting the ‘run’, just try to understand what the code is doing and try to link it with
the previous code.
2. Now ‘run’ the file and observe the results.

RESULT:

Explain (write) in your own words the cause and effects of what you just saw.

LAB TASKS:

1. Effects of Quantization with variable precision levels


Simulate a DTCV sampled composite signal of 𝑓𝑑1=125 samples/sec and
𝑓𝑑2=150 samples/sec with length of the signal be 250 samples.
Take the desired number of significant digits from user as an input. Then choose the method of
Quantization (round-off, floor & ceil) and apply to the signal generated above.
Compute the quantization error signals and SQNR.

2. Simple sinusoid quantized to various bits per sample


Generate a 100 Hz sinusoid sampled at 10000 samples/sec and quantized at 1_bit/sample.
Now increase the bit depth for various numbers of bits per sample (2, 3, 4, 5, 6, 7, 8) and attach
plots. You can use two column format for plotting (but the diagrams should be visible).

3. Audio signal quantization to various bits per sample


Use your recorded voice in last session and quantize it at 1 bit /sample.
Change bit depth to 2,3,4 and then listen and take notes of your observations.
Decide no. of bits for audio until quality stops improving.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 03
Discrete-Time Convolution

OBJECTIVE:

To study impulse response, observe convolution technique in signal processing, and verify
different properties like causality, commutative, distributive and associative properties.

THEORY:

1. Convolution is given as :y(n) = x(n)*h(n) =

i.e.one can compute the output y(n) to a certain input x(n) when impulse response h(n) of
that system is known. Convolution holds commutative property.

2. The length of the resulting convolution sequence is N+M-1,where N and M are the
lengths of two convolved signals respectively.

3. In causal system, the outputs only depend on the past and/or present values of inputs and
NOT on future values. This means that the impulse response h(n) of a causal system will
always exist only for n≥ 0.

PROCEDURE:

1. We have the impulse response of a system as h(n) = { 3,2,1,-2,1,0,-4,0,3}



2. For x(n)={1,-2,3,-4,3,2,1}

STEPS:
1. Make a folder at desktop and name it as your current directory within MATLAB.
2. Open M-file editor and write the following code:
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

clear all;
close all;
clc;
h = [3 2 1 -2 1 0 -4 0 3]; % impulse response
org_h = 1; % Sample number where origin exists
nh = [0 : length(h)-1]- org_h + 1;
x = [1 -2 3 -4 3 2 1]; % input sequence
org_x = 1; % Sample number where origin exists
nx = [0 : length(x)-1]- org_x + 1;
y = conv(h,x);

ny = [nh(1)+ nx(1) : nh(end)+nx(end)];


figure,

subplot(3,1,1),
stem(nh,h);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nh(1)-1 nh(end)+1]);
title('Impulse Response h(n)');
grid;

subplot(3,1,2),
stem(nx,x);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Input Signal x(n)');
grid;

subplot(3,1,3)
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Output Obtained by Convolution');
grid;

1. Save the file as P031.m in your current directory and ‘run’ it.
2. Calculate the length of input signal (N) and impulse response (M) used in above task?
3. Calculate the length of the output sequence and verify the result with N+M-1
4. Try to learn, explore the code and make notes.
5. Now modify the above code such that h(n)= {3,2, 1, -2,1,0,-4,0,3}(origin is shifted) and
check for causality.

Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

RESULT:

EXERCISE:

1. What will happen if we input x(n)={0,0,1,0,0} into the above system.



2. Can you prove the commutative property of the convolution?

3. Modify the code to prove Associative and Distributed properties of the convolution.

4. Convolve your recorded sound with drumloop.wav. Note your observation

a) Plot the output.


b) Listen the output
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 04

Discrete-Time Correlation

OBJECTIVE:

To study discrete time correlation and apply it to real data to observe the correlation
between two signals.

THEORY:

1. Correlation is given as where ‘l’ is the lag. This is called cross-correlation and it
gives the magniyude and location of similarity between two signals. The
correlation between x(n) and y(n) . It is given as:

2. Generally rxy(l) = ryx(l). These two are the same when x(n) and y(n) are the same signals
or when x(n) and y(n) are even symmetric signals .

3. The length of the resulting correlation sequence is N+M-1, where N and M are the
lengths of the two signals.

4. Correlation may also be computed using convolution algorithm with a modification that
we need to fold one of the signals before applying convolution.
Mathematically, rxy(n)= x(n) * y(-n)

STEPS:

1. Generate two sinusoids of length 10 and fd = 0.1 with variable phase.


2. Apply correlation and check for certain properties such as magnitude and location of
maximum correlation with varying phases.

PROCEDURE:

1.Make a folder at desktop and name it as your current directory within MATLAB. -
2.Open M-file editor and write the following code: )
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

clear all;
close all;
clc;
n = [0:9];
ph1 = 0;
ph2 = 0;
x = sin(2*pi*0.1*n + ph1);
org_x = 1;
nx = [0 : length(x)-1]- org_x + 1;

y = sin(2*pi*0.1*n + ph2);
org_y = 1;
ny = [0 : length(y)-1]- org_y + 1;

rxy = xcorr(x,y);
nr = [nx(1)-ny(end) : nx(end)-ny(1)];

[maxR indR] = max(rxy);

disp(['The correlation at lag zero is: ' num2str(rxy(find(nr==0)))


'.']);
disp(['The maximum correlation is at lag ' num2str(nr(indR)) '.']);
|
figure,
subplot(3,1,1),
stem(nx,x);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Signal x(n)');
grid;

subplot(3,1,2),
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Signal y(n)');
grid;

subplot(3,1,3)
stem(nr,rxy);
xlabel('Time index n');
ylabel('Amplitude');
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

xlim([nr(1)-1 nr(end)+1]);
title('Cross Correlation');
grid;

Save the file as P041.m in your current directory and ‘run’ it.

Learn the specific logical bits of the code and make notes

Now modify the phase of the second signal to pi/2 (it will make it cosine) and observe the
correlation at lag zero. Modify the phase again to ‘pi’ and observe.

1. Check for auto-correlation (ph1 = ph2) that the lag zero value gives the energy of the
Signal.
2. Observe that the commutative property does not hold.

RESULT:

Please write in exercise book.

EXERCISE:

1. Now modify the phase of the second signal to pi/2 (it will make it cosine)and observe the
correlation at lag zero.
2. Modify the phase again to ‘pi’ and observe.
3. Check for auto-correlation (ph1 = ph2) that the lag zero value gives the m energy of the
signal.
4. Observe that the commutative property does not hold.
5. Modify the code, such that the correlation is obtained using convolution command.
6. Calculate correlation between voltages of any two phases of a 10HP motor Using the data
given below. First use Ms. Excel to copy data and then calculate correlation.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

Voltage A Min Voltage B Min Voltage C Min


189.358 153.917 195.735
189.175 159.719 201.877
188.783 161.575 186.718
188.757 172.186 187.659
176.995 173.206 205.876
180.472 176.865 204.831
180.524 176.917 192.494
180.262 189.28 199.839
181.778 189.828 211.887
179.975 189.462 211.94
178.642 189.253 212.462
180.315 188.94 193.749
180.707 190.377 200.492
180.262 190.194 201.433
180.628 190.064 202.635
180.315 189.907 200.701
179.635 189.541 203.289
179.243 189.567 202.635
179.4 189.619 200.989
180.576 189.044 197.591
180.837 189.123 199.865
180.184 189.332 201.093
180.08 189.097 201.041
177.675 189.044 199.656
175.297 189.018 198.558
173.99 189.123 204.595
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 05
Effects of Re-Sampling in Discrete Time Signals.

OBJECTIVE:
To study the process of sampling rate conversion of discrete signal and to note the effect of
sampling rate conversion in a real audio signal.

THEORY:
The process of converting a signal from a given sampling rate to a different sampling rate is called
sampling rate conversion. Systems that employ multiple sampling rate in the processing of digital
signals are called multi_rate digital signal processing systems. In a multi-rate DSP system
whenever a signal with one sampling rate used by a system that needs a different rate, sampling
rate has to be increased or decreased.

UP-SAMPLING
It is a process used to increase the sampling rate by an integer factor.
Up-sampling operation is implemented by inserting equidistant zero-valued samples between two
consecutive samples of x[n] .
In practice, the zero-valued samples inserted by the up-sampler are replaced with appropriate
nonzero values using some type of filtering process .Process is called zero stuffing.
Second method for up sampling is interpolation
Up_Sampler Used to increase the sampling rate by an integer factor

An up-sampler with an up-sampling factor L, where L is a positive integer, develops an output


sequence with a sampling rate that is L times larger than that of the input sequence x[n].
𝐹𝑠𝑛ew = 𝐹𝑠𝑜ld * 𝐿
where, L=up-sampling factor.
Input-output relation
 x[n /L], n  0,  L,  2 L,
xu [n]  
 0, otherwise

DOWN-SAMPLING:
It is a process used to decrease the sampling rate by an integer factor.
Down-sampler - Used to decrease the sampling rate by an integer factor
A down-sampler with a down-sampling factor M, where M is a positive integer, develops an
output sequence y[n] with a sampling rate that is (1/M)-th of that of the input sequence x[n].
Down-sampling operation is implemented by keeping every M-th sample of x[n] and removing
in-between samples to generate y[n]
Input-output relation
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

y[n] = x[nM]

A down sampler realizes a sampling rate conversion by an integer factor M [M=down-sampling


factor] i.e. 𝐹snew = 𝐹𝑠𝑜ld ⁄𝑀, by retaining only every Mth input signal sample in the output
signal and discarding the M-1 samples in between i.e. 𝑥𝑑 = 𝑥𝑛ew (𝑛) = 𝑥𝑜ld (𝑀n).
In case of down-sampling, some data samples of 𝑥𝑜ld (𝑛) are lost and it mostly used in such
cases when we have so much redundant data in a discrete signal.

RE-SAMPLING
Mostly we are required to implement both down_sampling and up_sampling to obtain the
sampling rate by a fractional value that can be expressed as a ratio. For example, to resample by
a factor of 1.5, we can interpolate by a factor of 3 then decimate (down_sample) by a factor of 2
(to change the sampling rate by a factor of 3/2=1.5).
𝐹𝑠𝑛ew = 𝐹𝑠𝑜ld ∗ (𝐿⁄𝑀)

TASK-1
1. Generate 50 sample of a sinusoid with fd=0.12 .
2. Up sample it by a factor of 6 using zero stuffing method.
PROCEDURE:

clf;
clear all;
clc;
close all;
n = 0:50;
x = sin(2*pi*0.12*n);
y = zeros(1, 6*length(x));
y([1: 6: length(y)]) = x;
subplot(2,1,1)
stem(n,x);
title('Input Sequence');
xlabel('Time index n');ylabel('Amplitude');
subplot(2,1,2)
stem(n,y(1:length(x)));
title('Output Sequence');
xlabel('Time index n');ylabel('Amplitude');
Task-2: Re-Sampling (Up sampling: Zero stuffing) of Sinusoids by an integer factor
a) Generate a composite signal of 100 Hz and 200Hz sinusoid originally sampled at Fs=1000 Hz.
b) Plot it in discrete form for two complete cycles.
c) Now up-sample the original signal such that the effective sampling rate will become Fs'=4000
Hz.
d) Observe and note the effects of up-sampling.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

clear all;close all;clc;


F1 = 100;
F2 = 200;
Fs = 1000;
Ts = 1/Fs;
nTs = [0:Ts:2/F1];
x = sin(2*pi*F1*nTs)+sin(2*pi*F2*nTs);
L = 4; % Upsampling Factor
Tsup= Ts/L;
xup = upsample(x,L);
nup = [0:length(xup)-1];
tup = nup*Tsup;
figure
subplot(211)
stem(nTs,x,'k','Markerfacecolor','r','Linewidth',2);
xlabel('Discrete time (sec)'), ylabel('Amplitude'),axis tight,
grid,
legend('Original signal')
title('Original Signal')
subplot(212)
stem(tup,xup,'k','Markerfacecolor','r','Linewidth',2)
xlabel('Discrete time (sec)'), ylabel('Amplitude'),axis tight,
grid,
legend('Upsampled signal')
title('Zero Stuffing')

Task-3: Re-Sampling (Up sampling: Interpolation) of Sinusoids by an integer factor


Repeat Task-2 such that the interpolation method is used for increasing sampling rate.

clear all;close all;clc;


F1 = 100;
F2 = 200;
Fs = 1000;
Ts = 1/Fs;
nTs = [0:Ts:2/F1];
x = sin(2*pi*F1*nTs) + sin(2*pi*F2*nTs);
L = 4; % Upsampling Factor
Tsup= Ts/L;
xup = interp(x,L);
nup = [0:length(xup)-1];
tup = nup*Tsup;
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

figure
subplot(211)
stem(nTs,x,'k','Markerfacecolor','r','Linewidth',2)
xlabel('Discrete time (sec)'), ylabel('Amplitude'),axis tight,
grid,
legend('Original signal')
title('Original Signal')
subplot(212)
stem(tup,xup,'k','Markerfacecolor','r','Linewidth',2)
xlabel('Discrete time (sec)'), ylabel('Amplitude'),axis tight,
grid,
legend('Upsampled signal')
title('Interpolation')

Task-4: Re-Sampling (Downsampling) of Sinusoids by an integer factor


a) Generate a composite signal of 100 Hz and 200Hz sinusoid originally sampled at Fs=8000 Hz.
b) Plot it in discrete form for two complete cycles.
c) Now down sample the original signal such that the effective sampling rate will become
Fs'=2000 Hz.

clear all;close all;clc;


F1 = 100;
F2 = 200;
Fs = 8000;
Ts = 1/Fs;
nTs = [0:Ts:2/F1];
x = sin(2*pi*F1*nTs)+sin(2*pi*F2*nTs);
M = 4; % Downsampling Factor
Tsdown = M*Ts;
xdown = downsample(x,M);
ndown = [0:length(xdown)-1];
tdown = ndown*Tsdown;
figure;
stem(nTs,x,'m','Markerfacecolor','c')
hold
stem(tdown,xdown,'k','filled','LineWidth',2)
xlabel('Discrete time (sec)'), ylabel('Amplitude'),axis tight,
grid
legend('Original signal','Downsampled signal')
title('Downsampling')
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

Task-5: Re-Sampling (Downsampling) of Sinusoids by an integer factor


a) Generate a composite signal of 100 Hz and 200Hz sinusoid originally sampled at Fs=8000 Hz.
b) Plot it in discrete form for two complete cycles.
c) Now down sample the original signal such that the effective sampling rate will become
Fs'=2000 Hz.

clear all;close all;clc;


F1 = 100;
F2 = 200;
Fs = 8000;
Ts = 1/Fs;
nTs = [0:Ts:2/F1];
x = sin(2*pi*F1*nTs)+sin(2*pi*F2*nTs);
M = 4; % Downsampling Factor
Tsdown = M*Ts;
xdown = downsample(x,M);
ndown = [0:length(xdown)-1];
tdown = ndown*Tsdown;
figure;
stem(nTs,x,'m','Markerfacecolor','c')
hold
stem(tdown,xdown,'k','filled','LineWidth',2)
xlabel('Discrete time (sec)'), ylabel('Amplitude'),axis tight,
grid
legend('Original signal','Downsampled signal')
title('Downsampling')

Task-6: Re Sampling (Down sampling & up sampling) of Sinusoids by a Fractional factor

a) Generate a 1Hz signal originally sampled at 20Hz. Now convert the original sampling rate
so that effective sampling rate will become 30Hz.
b) Attach plot and make notes.

clear all, close all;clc;


% Sampling rate conversion by L/M = 3/2
F = 1;
Fs = 20; % Original sampling frequency in Hz
Ts = 1/Fs; % Original sampling period in seconds
nTs = [0:Ts:1]; % Time vector tx
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

x = 0.7*sin(2*pi*F*nTs)
figure;
stem(nTs,x); % Original sequence
L = 3; % Interpolation Factor
M = 2; % Downsample Factor
y = resample(x,L,M); % Re-sampling
Ts1= (Ts*M)/L;
ty = [0:length(y)-1]*Ts1; % New time vector ty
figure
stem(nTs,x,'*', 'Linewidth',2)
hold on
stem(ty,y,'-.r', 'filled')
xlabel('Time(sec)'), ylabel('Amplitude'), axis tight, grid,
legend('Original signal','Resampled signal'),
title('Original and Resampled signals')

EXERCISE:

1. Write values of corresponding input and output sequences to prove lab task 2.you may use
following table to note data. Also prove that value of up sampling factor.

Y(1)= X(?)= X(?)= X(?)=


Y(2)= X(?)= X(?)= X(?)=
Y(3)= X(?)= X(?)= X(?)=
Y(4)= X(?)= X(?)= X(?)=
Y(5)= X(?)= X(?)= X(?)=
Y(6)= X(?)= X(?)= X(?)=

Task-2: Resampling of Speech signals in MATLAB

Record your voice at sampling rate of 11025 Hz. Now down-sample and upsample the recorded
speech signal by different factors and observes the quality of re-sampled signals. Use this code:
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

clear all;close ;cic;


[y Fs bits] = wavread('speech.way');% Use file name of your recorded speech
M=2;% Downsampling Factor
L=2;% Upsampling Factor
yd = downsample(y,M);
yu = upsample(y,L);% You can use interp as well
sound(y,Fs)
pause(2)
sound(yd,Fs)
Now answer the given questions:
pause(2)
sound(yu,Fs)
a. Describe what you heard.
b. What changes in playback
waywrite(yd,Fs,bits,'dn2');%Use rate in file
different the names
sound for
(yd,different
Fs ) andM sound
values (yu, Fs) are
waywrite(yu,Fs,bits,'up2');%Use different file names
necessary to make the audio sound just right? for different L values
c. What changes in wavwrite are necessary to generate correct multimedia files?
d. Write the reason for the post lab task 2(b) above.
Now draw the tables and fill them:

Tablel: Observations of Downsampling in Speech signals

Effective quality during


Sr.No Down sampling Sampling Compensated playback File size in
Factor M Frequency playback rate [Good/OK/Bad kilobytes
]
1 2
2 3
3 4

4 5

5 6
6 7
7 8
8 9
9 10
10 11
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

Tablet: Observations of Upsampling in Speech signals


Effective Voice quality
Sr. No. Upsampling Compensated File size in
Sampling during playback
Factor [L] playback rate kilobytes
Frequency [Good/OK/Bad]
1 2

2 3
3 4
4 5
5 6
6 7

7 8
8 9
9 10

10 11

e) Mention both the maximum downsampling limit (factor) and upsampling limit (factor)
in speech signal and also specify the reasons.

f) Attach spectrum of all multimedia files of original, downsampled and upsampled


versions e.g. speech.wav, dn2.wav, up2.wav, dn3.wav, up3.wav, dn4.wav, up4.wav,
and so on by using the 'plot spectrum' in Audacity®. Use two column format for the
plotting of figures. Use small sized figures (they should be readable).
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 06

The Discrete Fourier Transform as a Linear Transformation

OBJECTIVE:

To study the computer implementation of Discrete FourierT transform and Inverse Fourier
Transform using Twiddle factor.

THEORY:

The formulas for the DFT and IDFT are given as


∑𝑁−1 𝑘𝑛
X(K) = 𝑛=0 𝑥(𝑛) 𝑊𝑁 ; k=0,1,……N-1

1 −𝑘𝑛
X(n) = ∑𝑁−1
𝑛=0 𝑋(𝑘) 𝑊𝑁 ; k=0,1,……N-1
𝑁

−𝑗2𝛱
Where by definition WN = 𝑒 𝑁

Which is an Nth root of unity. Where WN is called Twiddle Factor , also

[WN] = [𝑒 −𝑗2𝛱/𝑁 ]kn

𝑘𝑛
W = 𝑒 −𝑗2𝛱𝑘𝑛/𝑁
𝑁

DFT analysis equation in matrix form is

𝑘𝑛
XN=[ W ]xN
𝑁

DFT synthesis equation in matrix form is

𝑘𝑛 -1
xN= [W ] XN
𝑁
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

PROCEDURE:

TASK
Compute 4 point DFT of x(n)= ( 1,2,3,0).

STEPS
1.Generate given sequence in Matlab .
2.Take N-=4 to calculate 4-point DFT.
3.Define 0: N-1 point vector for time and frequency samples.
4.Define W matrix and then use DFT analysis equation to compute DFT.

close all,
clear all;
clc;
x=[1 ,2 ,3 ,0];
N=4;
n=[0:1:N-1];
k=[0:1:N-1];

WN=exp(-j*2*pi/N);

nk=n'*k;

WNnk=WN.^nk;

Xk=x*WNnk

LAB TASK

Prove DFT synthesis equation using DFT output generated from lab task.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 07

Studying Discrete Fourier Transform using an audio signal


OBJECTIVE:
To observe/find different frequency components in an audio signal and plot it with different x_
axes .

THEORY:

PROCEDURE:

1. Load an audio file ‘noisy.wav’ into Matlab.


2. There is a tone added to the speech in this file. The objective is to find the frequency of
this tone.
3. Computing the DFT of this signal;
4. Generating frequency vector in Hz.
5. Displaying the DFT and observing the frequency of the added tone.

STEPS
1. Make a folder at desktop and name it as your current directory within MATLAB.
2. Copy the audio file ‘noisy.wav’ into your current directory.
3. Open M file editor and write the following code:
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

clear all; clc; close all;


[y,Fs,bits] = wavread('noisy.wav');
Ts = 1/Fs;
n = [0:length(y)-1];
t = n.*Ts; k = n;
Df = Fs./length(y);
F = k.*Df;
Y = fft(y);
magY = abs(Y);
sound(y,Fs);
figure,

subplot(2,1,1);
plot(F,magY);
grid on;
xlim([0 Fs/2]);
xlabel('Frequency (Hz)');
ylabel('DFT Magnitude');
title('Discrete Fourier Transform');

subplot(2,1,2);
plot(F,magY);
grid on;

xlim([0 2000]);
xlabel('Frequency (Hz)');
ylabel('DFT Magnitude');
title('Discrete Fourier
Transform');

4. Save the file as P081.m in your current directory and run it.

RESULT:

Explore and take notes.

EXERCISE:

Use recorded data,


1. Plot different frequencies present in it with
a) x-axis as time
b )x-axis as frequency. (Take FFT and plot).
2. Calculate the amount of energy present in fundamental frequency.
3. Calculate the amount of energy present in different harmonics.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 08

Relationship between Laplace and CTFT

OBJECTIVE:
To study s-plane and plot impulse and frequency response for different pole zero location in s-
plane. Also to determine weather system is FIR or IIR.

THEORY:
The Laplace Transform of a general continuous time signal x (t) is defined as;
-st


X(S) = x(t) e dt.

Where the complex variable s=δ+ j w, with δ and w the real and imaginary parts. CTFT is a
subset of Laplace when δ =0. Since ‘δ’ information is not present in CTFT, therefore information
about stability can only be obtained from Laplace. If pole lies on L.H.S of s-plane, system is
stable. If pole lies on R.H.S of s-plane, system is unstable. If pole lies on y(jw)-axis, system is
marginally stable or oscillatory. If system has FIR, it is stable. If system is IIR, it can be stable or
unstable.

PROCEDURE:
Generate pole zero constellation in s plane.
1. Plot corresponding Frequency (Bode magnitude) response.
2. Plot impulse response and determine that the system is FIR or IIR.
3. Modify location of poles in s plane to observe the corresponding change in frequency and
impulse response.

STEPS.
1. Make a folder at desktop and name it as your current directory within MATLAB.
2. Open M-file editor and write the following code:

clear all;
close all;
clc;
Num = poly([(0-(i*(pi/2))),(0+(i*(pi/2)))]);
Zeros=roots(Num)
Den = poly([-1,-1]);
poles=roots(Den) sys=tf(Num,Den)

figure;
subplot(3,1,1);
pzmap(sys);
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

xlim([-2 2]);
ylim([-4 4]);
subplot(3,1,2);
[mag phase w]=bode(sys);
mag=squeeze(mag);
plot(w,mag);

subplot(3,1,3);
impulse(sys);
H=dfilt.df1(Num,Den);A=isfir(H)

3. Save the file as P091.m in your current directory and ‘run’ it.

RESULT:

1. Learn the specific logical bits of the code and make notes.
2. Observe the plots.
3. Now, explain (write) in your own words the cause and effects of what you just saw.

EXERCISE:

Change the location of poles from L.H.S of s-plane to y axis first, and then to R.H.S of s-
plane and observe the effects.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 09

Relationship between z transform and DTFT

OBJECTIVE:

To study z-plane and plot impulse and frequency response for different pole zero location in z-
plane.Also to determine weather system is FIR or IIR.

THEORY:

The z - Transform of a general discrete time signal x(n) is defined as;

X (z) = ∑∞
𝑛=𝑜 𝑥 (𝑛) z
-n

Where the complex variable z=r ∠w , with r the radius and w the angle. DTFT is a subset of z
transform when r =1. Since ‘r’ information is not present in DTFT, therefore information about
stability in discrete time can only be obtained from z transform. If pole lies inside the unit circle,
system is stable. If pole lies outside the unit circle, system is unstable. If pole lies at the unit
circle, system is marginally stable or oscillatory. If system has FIR, it is stable. If system is IIR,
it can be stable or unstable.

PROCEDURE:

1. Generate pole zero constellation in z plane.


2. Plot corresponding Frequency (Bode magnitude) response.
3. Plot impulse response and determine that the system is FIR or IIR.
4. Modify location of poles in z plane to observe the corresponding change in frequency and
impulse response.

STEPS:

1. Make a folder at desktop and name it as your current directory within MATLAB.
2. Open M-file editor and write the following code:

clear all;
close all;
clc;
Num = poly([(0-(i*(pi/2))),(0+(i*(pi/2)))]);
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

Den = poly([-1,-1]);
Num1 = poly([j,-j]);
Den1 = poly([exp(-1),exp(-1)]);
sys1=tf(Num1,Den1,1)

figure;
subplot(3,1,1);
pzmap(sys1);
xlim([-2 2]);
ylim([-4 4]);
subplot(3,1,2);
[mag phase w]=bode(sys1);

mag=squeeze(mag);
plot(w,mag);
xlim([0 100])
subplot(3,1,3);
impulse(sys1);
H=dfilt.df1(Num,Den);
A=isfir(H)
figure;
pzmap(sys1)
grid on;

3. Save the file as P010.m in your current directory and ‘run’ it.

RESULT:

1 Learn the specific logical bits of the code and make notes.
2 Observe the plots.
3 Now, explain (write) in your own words the cause and effects of what you just saw.

EXERCISE:

Change the location of poles from inside the unit circle to outside and at the unit circle and
observe and note the changes.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 10

Designing FIR using windowing

OBJECTIVE:
Object of this lab is introduction to digital filters and its types, design FIR filter and study how it
performs filtering on a signal. Further truncate different types of FIR filter like Low Pass, High
Pass, Band Pass using different windows like rectangular, Kaiser Etc. and compare the results
obtained from different windows.

THEORY:
The process of deriving a realizable transfer function of a digital filter by considering given
frequency response specifications is known as digital filter design. The digital filter can be
classified as:

1. Finite –duration impulse response (FIR) filter


2. Infinite –duration impulse response (IIR) filter
In MATLAB, there are built in functions which can be used to design digital filter like IIR and
FIR.

The different types of FIR filters are listed as follows:

 Window techniques based FIR filter.


1. Rectangular windows.
2. Hamming window.
3. Hanning window.
4. Blackman window.
5. Barlett window.
6. Kaiser window.
 Equiripple linear phase FIR filter.
 Least square error FIR filters.

The different types of IIR filters are listed as follows:

 Butterworth filter
 Chebyshev Type I filter
 Chebyshev Type II filter
 Elliptic filter
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

FIR digital filter operates on digital sample values. It uses current and past input samples to
produce a current output sample. It does not use previous output samples. There are various
types of FIR filter based on need viz. low pass, high pass, band pass and band stop, Low pass
filter.

Following points are usually considered to design FIR filter other the window type.
INPUT:
• Window Type
• Passband and stopband ripples
• passband and stopband edge frequencies
• sampling frequency
• order of the filter
• window coefficients

OUTPUT:
• magnitude and phase responses

COMPARISON OF FIR AND IIR FILTERS


1. FIR filters are Finite Impulse Response filters with no feedback, whereas IIR contains
feedback.
2. Transfer function of FIR filter does not contain any non-trivial poles. Their frequency
response is solely dependent on zero locations. IIR filters contain poles as well as zeros.
3. As there are no poles, FIR filters cannot become unstable; however, IIR filters can
become unstable if any pole lies outside the unit circle in z-plane.
4. More number of coefficients is needed to design the desired filter in FIR than IIR.

PROCEDURE:
TASK-1

1. Create a signal vector containing two frequencies as:


i) 100 Hz. and ii) 150 Hz. with Fs = 1000 Hz.
2. Design two band pass FIR filters with 64 coefficients and with pass bands as i) 125 to
175 Hz. and ii) 75 to 125 Hz.
3. Use both filters on the created signal and observe their outputs.
4. Plot frequency responses and pole-zero constellations of both filters and note
observations.

close all; clear all; clc; % Frequencies in Hz.


Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

F1 = 100; F2 = 150;

% Sampling Frequency in samples/sec.

Fs = 1000;

t = [0 : 1/Fs : 1]; % Time Vector


F = Fs*[0:length(t)-1]/length(t); % Frequency Vector

x = exp(j*2*pi*F1*t)+2*exp(j*2*pi*F2*t); % Signal Vector

bh = fir1( 64 , [125 175]/500); % filter coeffs.


bl = fir1( 64 , [75 125]/500); % filter coeffs.
[hh,wh]=freqz(bh,1,length(t),'whole'); % Frequency
response for filter 1
[hl,wl]=freqz(bl,1,length(t),'whole'); % Frequency
response for filter 2
% Filter operation - see filtfilt in help to learn what it
does

yh = filtfilt(bh,1,x);
yl = filtfilt(bl,1,x);

% Plotting

figure, subplot(5,1,1),

plot(F,abs(fft(x)));

xlim([0 Fs/2]);
title('FFT of original signal');

subplot(5,1,2),
plot(F,abs(hh));
xlim([0 Fs/2]);
title('Frequency response of Filter One');

subplot(5,1,3),
plot(F,abs(fft(yh)));
xlim([0 Fs/2]);
title('FFT of filtered signal from filter one');

subplot(5,1,4),
plot(F,abs(hl));
xlim([0 Fs/2]);
title('Frequency response of Filter Two');

subplot(5,1,5),
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

plot(F,abs(fft(yl)));
xlim([0 Fs/2]);
title('FFT of filtered signal from filter two');
xlabel('Hz.')

% Pole Zero Constellations

[bh,ah] = eqtflength(bh,1);
[zh,ph,kh] = tf2zp(bh,ah);
[bl,al] = eqtflength(bl,1);
[zl,pl,kl] = tf2zp(bl,al);

figure,
subplot(1,2,1),
pzplane(bh,ah);
xlim([-1.5 1.5]);
ylim([-1.5 1.5]);
title('Filter_One');
subplot(1,2,2),
pzplane(bl,al);
xlim([-1.5 1.5]);
ylim([-1.5 1.5]);
title('Filter Two');

TASK -2
Write a program to design a FIR filter using Hanning windows,take inputs from user for design
values of filter.

close all;
clear all;
clc;

fp=input('Enter the pass band frequency');


fs=input('Enter the stop band frequency');
rp=input(' Enter the pass band attenuation');
rs=input('Enter the stop band attenuation');
f=input(' Enter the sampling frequency');

% Calculating filter order

num=-20*log10(sqrt(rp*rs))-13;
dem=14.6*(fs-fp)/f;
n=ceil(num/dem);
n=abs(n);
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

% Normalizing the frequencies

wp=2*fp/f;
ws=2*fs/f;
wn=(ws+wp)/2;

%Adjusting the filter order. The order of window must be an odd


number
%and the order of filter must be one less than that of the
window

if (rem(n,2)==0)
m=n+1;
else
m=n;
n=n-1;
end

%Window sequence calculation

w=hann(m);

%Calculation of filter coefficients

b=fir1(n,wn,'low',w);

%Plotting the filter response

freqz(b,1,500,3000);
TITLE('Magnitude and Phase response');

TASK-3
Write a program for FIR(Finite Impulse Response) filter like Low pass FIR filter, High pass FIR
filter, Band pass FIR filter and Band stop FIR filter using Rectangular window using MATLAB .

ALGORITHM:
LOW PASS FILTER:
Step 1: Read the input sequence
Step 2: Perform low pass filter calculations
Step 3: Plot the output sequences

HIGH PASS FILTER:


Step 1: Read the input sequence
Step 2: Perform high pass filter calculations
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

Step 3: Plot the output sequences

BAND PASS FILTER:


Step 1: Read the input sequence
Step 2: Perform band pass filter calculations
Step 3: Plot the output sequences

BAND STOP FILTER:


Step 1: Read the input sequence
Step 2: Perform band stop filter calculations
Step 3: Plot the output sequences

PROGRAM:
clc;
clear all;
close all;
rp=input('Enter the passband ripple(rp):');
rs=input('Enter the stopband ripple(rs):');
fp=input('Enter the passband frequency(fp):');
fs=input('Enter the stopband frequency(fs):');
f=input('Enter the sampling frequency(f):');
wp=2*fp/f;
ws=2*fs/f;
num=-20*log10(sqrt(rp*rs))-13;
dem=14.6*(fs-fp)/f;
n=ceil(num/dem);
n1=n+1;
if(rem(n,2)~=0)
n1=n;
n=n-1;
end
y=boxcar(n1);
%Low pass filter
b=fir1(n,wp,y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,1);
plot(m);
ylabel('Gain(db)->');
xlabel('(a)Normalised frequency->');
%High pass filter
b=fir1(n,wp,'high',y);
[h,o]=freqz(b,1,256);
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

m=20*log10(abs(h));

subplot(2,2,2);
plot(m);
ylabel('Gain(db)');
xlabel('(b)Normalised frequency');
%Band pass filter
wn=[wp*ws];
b=fir1(n,wn,y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,3);
plot(m);
ylabel('Gain(db)');
xlabel('(c)Normalised frequency');
%Band stop filter==============
wn=[wp*ws];
b=fir1(n,wn,'stop',y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,4);
plot(m);
ylabel('Gain(db)');
xlabel('(d)Normalised frequency-');

EXERCISE:
Q1. Perform Q3.using Hamming and Kaiser Window.
Compare results of designed filters using three different windows on a single plot.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

LAB SESSION 11

Designing IIR using Filter Design and analysis Tool (FDA tool)

OBJECTIVE:
Object of this lab is to design different IIR filter using FDA tool.

THEORY:
Filter Design and Analysis Tool (FDA Tool) is Graphic User Interface for designing and
analyzing filters. It is used to design FIR and IIR filters by entering the desired filter
specifications, or by importing filter from MATLAB workspace or by adding, moving or
deleting poles and zeros. After designing a filter, the response can be viewed and analyses in
other Graphic User Interface tool named Filter Visualization Tool (FV Tool) linked with FDA
Tool. The different types of responses that can be viewed are listed below:

 Magnitude response  Impulse response


 Phase response  Step response
 Group delay  Pole-zero plot
 Phase delay  Zero-phase plot

OPENING FDA TOOL WINDOW:


FDA Tool can be opened using command:
fdatool

Figure A
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

The different steps involved in designing a filter using FDA Tool can be listed as:

1. Selection of type of response required


2. Selection of type of filter design
3. Specifying the filter order
4. Entering the filter specifications
5. Entering the magnitude specifications

After providing the information listed above, filter can be designed and its response can be
viewed and analysed.

The complete description of the FDA Tool window and different steps required to design a
filter are elaborated below:
1. Selecting response type: The desired response type is selected from the list of available
options, i.e., lowpass, highpass, bandpass, bandstop, differentiation, multiband, peaking
etc.

2. Type of design method: The design can be of FIR or IIR filter. Depending upon whether
FIR Or IIR filter design is selected, further options are available in the dropdown menu.
In IIR filter design, the different options available in dropdown menu are as given below:

 Butterworth
 Chebyshev type I
 Chebyshev type II
 Elliptic
 Maximally flat
 Least Pth-norm
 Const least Pth-norm
In FIR filter design the options available are listed as follows:
 Equirriple
 Least square
 Window
 Const least squares
 Complex equiripple
 Least Pth norm
 Constrained equiripple
 Generalized equiripple
 Constrained band equirriple
 Interpolated FIR
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

The options available depend upon the selection of response type.

3. Filter order: Under this, two options available are as


 User-defined order: Under this option user has to enter the order of the filter.
 Minimum order: The other option available for selecting the filter order is
minimum order. It is calculated by system itself.

4. Filter specifications: Depending upon the response type and design method selected,
the graphical representation of generalized filter specifications appear in the display
region of FDA Tool. These specifications are ‘Frequency Specifications’ and
‘Magnitude Specification’.
These specifications are provided by the user, as per filter design requirement, in the
appropriate blocks.

5. Designing filter: After all the requisite information is entered, a filter can be designed by
clicking the ‘Design Filter’ button available at the bottom of the window. Filter |
coefficients are calculated and magnitude response appears in the display region.

(Note: ‘Design Filter’ button will be disabled once the filter coefficients are computed. This
button will be enabled again in case any changes are made in the filter specifications.)

6. Displaying filter responses: Once the filter coefficients are calcu

lated as per the specifications provided by the user, the display region will show
magnitude response of the designed filter. The other filter response characteristics
can be viewed in the display region or FV Tool. The response to be viewed can be
selected from the different icons displayed on the toolbar shown in Figure below.

Figure : Different Response Icons on the Toolbar

(NOTE: The different responses for display can also be selected from the
‘Analysis’ menu on menu bar.)

7. Current filter information: The information about the designed filter is given in
the ‘Current Filter Information’ region of FDA Tool window as shown
in Figure A The information provided is about the ‘structure’, ‘order’, ‘stability’ and
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

‘source’
 Storing a filter
The designed filter is stored by clicking ‘Store Filter’ button in the
‘Current Filter Information’ region.
 Filter manager
The ‘Filter Manager’ button opens up a new Filter Manager window
(Figure B) showing the list of filters stored. This window also has
options as: Edit current filter, Cascade, Rename, Remove and FV Tool.

Figure B Filter Manager Window

To cascade two or more filters, highlight the designed filters and press ‘Cascade’ button.
A new cascaded filter is added to the ‘Filter Manager’.

8. Saving and opening filter design session:


The filter design session is saved as MAT-file and can be used later on. It can be saved by
clicking save icon or selecting save session
option in File menu and giving desired session name. Similarly, the saved session
can be opened by clicking open icon or by selecting open option in file menu and
selecting the previously saved filter design session.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

FILTER VISUALIZATION TOOL:

The response characteristics can be viewed in a separate window by selecting the ‘Filter
Visualization Tool’ (FV Tool) from ‘view’ menu or clicking the ‘Full View Analysis’ button
on the toolbar. The FV Tool window is shown in Figure C

FV Tool has most of the menus on the menu bar and icons on the toolbar similar to that FDA
Tool with some additional icons which are mainly used to work with representation of the
responses.

Figure C Filter Visualization Tool(FV Tool) window


IIR FILTER DESIGN USING FDA TOOL
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

TASK-1
Design an IIR Butterworth band pass filter with the following
specifications:
Normalized pass band edges at 0.40 and 0.65
Normalized stop band edges at 0.3 and 0.75
Pass band ripple 1 dB
Minimum stop band attenuation 40 dB
Show (i) Magnitude response (ii) Phase response (iii) Group delay (iv) Phase delay response.
Solution:
As per the given specifications, the requisite data is entered in new FDA Tool window
as shown in Figure

Figure. FDA Tool Window Showing Specification Entered and Magnitude Response for Task-1.

The filter is designed for minimum order so as to reduce the complexity of the design.
In case, it has to be designed for user defined order, then the order of the filter has to be
calculated first by user using appropriate formulas or MATLAB function.
The other responses can be viewed by clicking on the appropriate icon on the toolbar and
responses obtained are shown in Figures below
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

Figure Magnitude Response in dB

Figure Phase Response


Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

Figure Group Delay Response

Figure. Phase Delay

These responses can also be viewed in FV Tool.


Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

TASK-2

Design a Type II Chebyshev IIR lowpass filter with the following specifications:
Passband frequency 1,200 Hz

Stopband frequency 1,700 Hz

Sampling frequency 6,000 Hz

Passband ripple 0.50 dB

1. Show magnitude response.


2. Show pole/zero plot.

Solution: FDA Tool Window showing given specifications duly entered and magnitude
response in response display region is shown in Figure.

Figure. FDA Tool Window for Example


Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

By using the FV Tool, the magnitude response and pole/zero plot is obtained as separate figures and is
shown in Figures.

Figure. Magnitude Response for Task-2.

Figure Pole/zero Plot for Q2


Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

TASK-3:
Design an elliptic IIR low pass filter with following specifications:
Pass band ripple 0.5 dB

Stop band attenuation 40 dB

Pass band frequency 800 Hz

Stop band frequency 1,000 Hz

Sampling frequency 4,000 Hz

1. Show magnitude and phase response in the same window.


2. Obtain filter information.
Solution:
As per given specifications, the requisite data is entered in FDA Tool window. By clicking
appropriate icon on toolbar, the magnitude and phase responses are obtained in the same window.
1. These magnitude and phase responses obtained are viewed in FV Tool window also and are
shown in Figure .
Figure . Magnitude and Phase Response for Task-3.

2. To obtain the information about the filter ‘Filter Information’ icon on Toolbar of FDA Tool
Window is clicked or ‘Filter Information’ option is selected from ‘Analysis’ menu. The detailed
filter information appears in the display region as shown in Figure a, b and c.
Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

Figure ‘Filter information’ for Task-2


Digital Signal Processing
NED University of Engineering & Technology Department of Electrical Engineering

The filter information is obtained by scrolling down the text in the window shown in Figure
15.41b.

EXERCISE:

Record Your Voice at home while turn any motor of your house ON.
Design a filter using FDA Tool.

Remove sound of motor from recorded signal.

Listen the output signal.

You might also like