You are on page 1of 50

CONTENTS

S.No
Exercise Page. No
1
Introduction
1
1
To find DFT of given signal
7
2
To find frequency response of given system
10
3
Impulse response of first order and second order
systems
12
4
Implementation of FFT of given sequence
14
5
Determination of power spectrum of given signal
18
6, 7
Implementation of low pass and High Pass FIR filter
20
8,9
Implementation of Low pass and high pass IIR filter
28
10
Generation of sinusoidal waveform based on recursive
difference equation/IIR filter
35
11
Generation of DTMF signal
38
12,13,
14
Implementation of Interpolation, decimation and I/D
sampling rate Converters
42


DSP Lab Manual
Dept of ECE VITAE, HYD 1
INRODUCTION
MATLAB: MATLAB is a software package for high performance numerical
computation and visualization provides an interactive environment with hundreds of built
in functions for technical computation, graphics and animation. The MATLAB name
stands for MATrix Laboratory
The diagram shows the main features and capabilities of MATLAB.

























MATLAB
Computations
Linear algebra
Signal processing
Polynomials & interpolation
Quadrature
Solution of ODEs
External interface
Interface with C and
Fortran programs
Graphics
2-D graphics
3-D graphics
Animation
Toolbox
Signal processing Image processing
Statistics Control system
Neural networks Communications
DSP Lab Manual
Dept of ECE VITAE, HYD 2
At its core ,MATLAB is essentially a set (a toolbox) of routines (called m files or
mex files) that sit on your computer and a window that allows you to create new
variables with names (e.g. voltage and time) and process those variables with any of
those routines (e.g. plot voltage against time, find the largest voltage, etc).

It also allows you to put a list of your processing requests together in a file and save that
combined list with a name so that you can run all of those commands in the same order at
some later time. Furthermore, it allows you to run such lists of commands such that you
pass in data and/or get data back out (i.e. the list of commands is like a function in most
programming languages). Once you save a function, it becomes part of your toolbox (i.e.
it now looks to you as if it were part of the basic toolbox that you started with).

For those with computer programming backgrounds: Note that MATLAB runs as an
interpretive language (like the old BASIC). That is, it does not need to be compiled. It
simply reads through each line of the function, executes it, and then goes on to the next
line. (In practice, a form of compilation occurs when you first run a function, so that it
can run faster the next time you run it.)

MATLAB Windows:
MATLAB works with through three basic windows
Command Window : This is the main window .it is characterized by MATLAB
command prompt >> when you launch the application program MATLAB puts you in
this window all commands including those for user-written programs ,are typed in this
window at the MATLAB prompt

Graphics window: the output of all graphics commands typed in the command window
are flushed to the graphics or figure window, a separate gray window with white
background color the user can create as many windows as the system memory will allow

Edit window: This is where you write edit, create and save your own programs in files
called M files.
DSP Lab Manual
Dept of ECE VITAE, HYD 3
Input-output:
MATLAB supports interactive computation taking the input from the screen and
flushing, the output to the screen. In addition it can read input files and write output files
Data Type: the fundamental data type in MATLAB is the array. It encompasses several
distinct data objects- integers, real numbers, matrices, charcter strings, structures and
cells.There is no need to declare variables as real or complex, MATLAB automatically
sets the variable to be real.
Dimensioning: Dimensioning is automatic in MATLAB. No dimension statements are
required for vectors or arrays .we can find the dimensions of an existing matrix or a
vector with the size and length commands.

Basic Instructions in Mat lab
1. T = 0: 1:10
This instruction indicates a vector T which as initial value 0 and final value
10 with an increment of 1
Therefore T = [0 1 2 3 4 5 6 7 8 9 10]

2. F= 20: 1: 100
Therefore F = [20 21 22 23 24 100]
3. T= 0:1/pi: 1
Therefore T= [0, 0.3183, 0.6366, 0.9549]
4. zeros (1, 3)
The above instruction creates a vector of one row and three columns whose
values are zero
Output= [0 0 0]
5. zeros( 2,4)
Output = 0 0 0 0
0 0 0 0
6. ones (5,2)
The above instruction creates a vector of five rows and two columns

DSP Lab Manual
Dept of ECE VITAE, HYD 4
Output = 1 1
1 1
1 1
1 1
1 1
7. a = [ 1 2 3]
b = [4 5 6]
a.*b = [4 10 18]
Which is multiplication of individual elements?
i.e. [4X1 5X2 6X3]
8 if C= [2 2 2]
b.*C results in [8 10 12]
9. plot (t, x)
If x = [6 7 8 9]
t = [1 2 3 4]

This instruction will display a figure window which indicates the plot of x versus t

9

8

7

6

1 2` 3 4

10. stem (t,x)


DSP Lab Manual
Dept of ECE VITAE, HYD 5
This instruction will display a figure window as shown

9
8
7
6

11. Subplot: This function divides the figure window into rows and columns
Subplot (2 2 1) divides the figure window into 2 rows and 2 columns 1
represent number of the figure








Subplot(3, 1, 3)








12 Filter
Syntax: y = filter(b,a,X)


1 2
(2 2 1) (2,2,2)


3 4
(2 2 3) ( 2 2 4)











1 (3, 1, 1)


2 (3, 1, 2)


3 (3, 1, 3)
DSP Lab Manual
Dept of ECE VITAE, HYD 6
Description: y = filter(b,a,X) filters the data in vector X with the filter described by
numerator coefficient vector b and denominator coefficient vector a.If a(1) is not equal to
1, filter normalizes the filter coefficients by a(1). If a(1) equals 0, filter returns an error.

13. Impz
Syntax: [h,t] = impz(b,a,n)
Description: [h,t] = impz(b,a,n) computes the impulse response of the filter with
numerator coefficients b and denominator coefficients a and computes n samples of the
impulse response when n is an integer (t = [0:n-1]'). If n is a vector of integers, impz
computes the impulse response at those integer locations, starting the response
computation from 0 (and t = n or t = [0 n]).If, instead of n, you include the empty vector
[] for the second argument, the number of samples is computed automatically by default.
14. Fliplr
Syntax: B = fliplr(A)
Description: B = fliplr(A) returns A with columns flipped in the left-right direction, that
is, about a vertical axis.If A is a row vector, then fliplr(A) returns a vector of the same
length with the order of its elements reversed. If A is a column vector, then fliplr(A)
simply returns A.
15. Conv
Syntax: w = conv(u,v)
Description: w = conv(u,v) convolves vectors u and v. Algebraically, convolution is the
same operation as multiplying the polynomials whose coefficients are the elements of u
and v.

16.Disp
Syntax: disp(X)
Description: disp(X) displays an array, without printing the array name. If X contains a
text string, the string is displayed.Another way to display an array on the screen is to type
its name, but this prints a leading "X=," which is not always desirable.Note that disp does
not display empty arrays.

DSP Lab Manual
Dept of ECE VITAE, HYD 7
17.xlabel
Syntax: xlabel('string')
Description: xlabel('string') labels the x-axis of the current axes.

18. ylabel
Syntax : ylabel('string')
Description: ylabel('string') labels the y-axis of the current axes.

19.Title
Syntax : title('string')
Description: title('string') outputs the string at the top and in the center of the current
axes.

20.grid on
Syntax : grid on
Description: grid on adds major grid lines to the current axes.
DSP Lab Manual
Dept of ECE VITAE, HYD 8
Experiment 1: To find DFT of given sequence

Aim: To find DFT of given sequence

Theory: Description
Fourier analysis is a family of mathematical techniques, all based on ecomposing signals
into sinusoids. The discrete Fourier transform (DFT) is the family member used with
digitized signals. A signal can be either continuous or discrete, and it can be either
periodic or Aperiodic. The combination of these two features generates the four
categories, described below
- Aperiodic-Continuous
This includes, decaying exponentials and the Gaussian curve. These signals extend to
both positive and negative infinity without repeating in a periodic pattern. The Fourier
Transform for this type of signal is simply called the Fourier Transform.
- Periodic-Continuous
This includes: sine waves, square waves, and any waveform that repeats itself in a regular
pattern from negative to positive infinity. This version of the Fourier transform is called
the Fourier series.
- Aperiodic-Discrete
These signals are only defined at discrete points between positive and negative
infinity,and do not repeat themselves in a periodic fashion. This type of Fourier transform
is called the Discrete Time Fourier Transform.
- Periodic-Discrete
These are discrete signals that repeat themselves in a periodic fashion from negative to
positive infinity. This class of Fourier Transform is sometimes called the Discrete Fourier
Series, but is most often called the Discrete Fourier Transform.

Discrete Fourier Transform Computation:
Mathematical Expression to calculate DFT for an input sequence x(n)

DSP Lab Manual
Dept of ECE VITAE, HYD 9

Matlab Code
clf;
a=[1 1 2 2];
x=fft(a,4);
n=0:3;
subplot(2,1,1);
stem(n,abs(x));
xlabel('time index n');ylabel('Amplitude');
title('amplitude obtained by dft');
grid;
subplot(2,1,2);stem(n,angle(x));
xlabel('time index n'); ylabel('Amplitude');
title('Phase obtained by dft');


DSP Lab Manual
Dept of ECE VITAE, HYD 10
Experiment No 2. To find frequency response of LTI system given in
transfer function / difference equation

Aim: To find frequency response of LTI system given in transfer function /
difference equation

% Frequency Response of LTI system using difference equation

clf;
num=input('numerator coefficiuents b = ');
den=input('denominator coefficients a = ');
w = -pi:8*pi/511:pi;
h = freqz(num, den, w);
% Plot the DTFT
subplot(2,1,1)
plot(w/pi,abs(h));grid
title('Magnitude of H')
xlabel('\omega /\pi');
ylabel('Amplitude');
subplot(2,1,2)
plot(w/pi,phase(h));grid
title('phase of H')
xlabel('\omega /\pi');
ylabel('phase');

Output

freqresp
numerator coefficiuents b = [2 1]
denominator coefficients a = [1 -0.6]

DSP Lab Manual
Dept of ECE VITAE, HYD 11




DSP Lab Manual
Dept of ECE VITAE, HYD 12
EXPERIMENT NO 3: Impulse response of a given system

Aim:
To find the impulse response h(n) of the given LTI system whose response y(n) to an
input x(n) is given.

Theory:

Fig.2.1 A LTI system

- A discrete time LTI system (also called digital filters) as shown in Fig.2.1 is
represented by
o A linear constant coefficient difference equation, for example,
]; 2 [ ] 1 [ ] [ ] 2 [ ] 1 [ ] [
2 1 0 2 1
+ + = + n x b n x b n x b n y a n y a n y
o A system function H(z) (obtained by applying Z transform to the
difference equation).
2
2
1
1
2
2
1
1 0
1 ) (
) (
) (


+ +
+ +
= =
z a z a
z b z b b
z X
z Y
z H
- Given the difference equation or H(z), the impulse response of the LTI system is
found using filter or impz MATLAB functions.

MATLAB Programs:
Program 1

b=input('numerator coefficiuents b = ');
a=input('denominator coefficients a = ');
n=input('enter length n = ');
[h,t] = impz(b,a,n);
disp(h);
DSP Lab Manual
Dept of ECE VITAE, HYD 13
stem(t,h);
xlabel('samples n ' ,'color' , 'm');
ylabel('amplitude h(n)','color','m');
title('impulse response','color','r');
grid on;

Result:
numerator coefficiuents b = [1]
denominator coefficients a = [1 -0.5]
enter length n = 20
1.0000 0.5000 0.2500 0.1250 0.0625 0.0313 0.0156 0.0078
0.0039 0.0020 0.0010 0.0005 0.0002 0.0001 0.0001 0.0000
0.0000 0.0000 0.0000 0.0000



DSP Lab Manual
Dept of ECE VITAE, HYD 14
Experiment No. 4 Implementation of N point FFT

Aim: To Implement FFT algorithm of a given sequence and to plot magnitude and
phase spectra

Theory:
- Discrete Fourier Transform (DFT) is used for performing frequency analysis of
discrete time signals. DFT gives a discrete frequency domain representation
whereas the other transforms are continuous in frequency domain.
- The N point DFT of discrete time signal x[n] is given by the equation
1 - N 0,1,2,.... k ; ] [ ) (
1 - N
0 n
2
= =

N
kn j
e n x k X
t

Where N is chosen such that L N > , where L=length of x[n].
- The inverse DFT allows us to recover the sequence x[n] from the frequency
samples.
1 - N 0,1,2,.... n ; ] [
1
] [
1
0
2
= =

=
N
k
N
kn j
e n x
N
n x
t

- X(k) is a complex number (remember e
jw
=cosw + jsinw). It has both magnitude
and phase which are plotted versus k. These plots are magnitude and phase
spectrum of x[n]. The k gives us the frequency information.
- Here k=N in the frequency domain corresponds to sampling frequency (fs).
Increasing N, increases the frequency resolution, i.e., it improves the spectral
characteristics of the sequence. For example if fs=8kHz and N=8 point DFT, then
in the resulting spectrum, k=1 corresponds to 1kHz frequency. For the same fs
and x[n], if N=80 point DFT is computed, then in the resulting spectrum, k=1
corresponds to 100Hz frequency. Hence, the resolution in frequency is increased.
- Since L N > , increasing N to 8 from 80 for the same x[n] implies x[n] is still the
same sequence (<8), the rest of x[n] is padded with zeros. This implies that there
is no further information in time domain, but the resulting spectrum has higher
frequency resolution. This spectrum is known as high density spectrum
(resulting from zero padding x[n]). Instead of zero padding, for higher N, if more
DSP Lab Manual
Dept of ECE VITAE, HYD 15
number of points of x[n] are taken (more data in time domain), then the resulting
spectrum is called a high resolution spectrum.

Algorithm:
1. Input the sequence for which DFT is to be computed.
2. Input the length of the DFT required (say 4, 8, >length of the sequence).
3. Implement FFT algorithm.
4. Plot the magnitude & phase spectra.

MATLAB Program:

% This programme is for fast fourier transform in matlab.
% Where y is the input argument and N is the legth of FFT . Let
% y = [1 2 3 4 ];
y=input('enter input sequence:');
N= input('size of fft(e.g . 2,4,8,16,32):');
n=length(y);
p=log2(N);
Y=y;
Y=[Y, zeros(1, N - n)];
N2=N/2;
YY = -pi*sqrt(-1)/N2;
WW = exp(YY);
JJ = 0 : N2-1;
W=WW.^JJ;
for L = 1 : p-1
u=Y(:,1:N2);
v=Y(:,N2+1:N);
t=u+v;
S=W.*(u-v);
Y=[t ; S];
DSP Lab Manual
Dept of ECE VITAE, HYD 16
U=W(:,1:2:N2);
W=[U ;U];
N=N2;
N2=N2/2;
end;
u=Y(:,1);
v=Y(:,2);
Y=[u+v;u-v];
Y
subplot(3,1,1)
stem(y);grid
title('input sequence y')
xlabel('n');
ylabel('Amplitude');
subplot(3,1,2)
stem(abs(Y));grid
title('Magnitude of FFT')
xlabel('N');
ylabel('Amplitude');
subplot (3,1,3)
stem(angle(Y));grid
title('phase of FFT')
xlabel('N');
ylabel('phase');

Result:
>> fft1
enter input sequence:[1 2 3 4 5 6 7]
size of fft(e.g . 2,4,8,16,32):8
Y =
28.0000
DSP Lab Manual
Dept of ECE VITAE, HYD 17
-9.6569 + 4.0000i
-4.0000 - 4.0000i
1.6569 - 4.0000i
4.0000
1.6569 + 4.0000i
-4.0000 + 4.0000i
-9.6569 - 4.0000i


DSP Lab Manual
Dept of ECE VITAE, HYD 18
Experiment No. 5 Power Density Spectrum Using MATLAB

Write a MATLAB program to compute Power Density Spectrum of a given signal

Algorithm:
1. Generate a signal
2. find DFT of the signal
3. PSD is given by the formula
y(n) =

=

k
n k x k x ) ( ) (
where n = - (N-1) to (N-1)
PSD= |Y(w)|
2

Where Y(w) = fft of y(n)

Matlab program
% computation of psd of signal corrupted with random noise
t = 0:0.001:0.6;
x = sin(2*pi*50*t)+sin(2*pi*120*t);
y = x + 2*randn(size(t));
figure,plot(1000*t(1:50),y(1:50))
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('time (milliseconds)');
Y = fft(y,512);
%The power spectral density, a measurement of the energy at various frequencies, is:
Pyy = Y.* conj(Y) / 512;
f = 1000*(0:256)/512;
figure,plot(f,Pyy(1:257))
title('power spectrum of y');
xlabel('frequency (Hz)');

DSP Lab Manual
Dept of ECE VITAE, HYD 19
Output


DSP Lab Manual
Dept of ECE VITAE, HYD 20

Experiment No. 6 and 7 Design and implementation of FIR filter to
meet given specifications

Aim: To design and implement a FIR filter for given specifications.

Theory:
There are two types of systems Digital filters (perform signal filtering in time domain)
and spectrum analyzers (provide signal representation in the frequency domain). The
design of a digital filter is carried out in 3 steps- specifications, approximations and
implementation.

DESIGNING AN FIR FILTER (using window method):

Method I: Given the order N, cutoff frequency fc, sampling frequency fs and the
window.
- Step 1: Compute the digital cut-off frequency Wc (in the range - < Wc < , with
corresponding to fs/2) for fc and fs in Hz. For example let fc=400Hz,
fs=8000Hz
Wc = 2** fc / fs = 2* * 400/8000 = 0.1* radians
For MATLAB the Normalized cut-off frequency is in the range 0 and 1, where 1
corresponds to fs/2 (i.e.,fmax)). Hence to use the MATLAB commands
wc = fc / (fs/2) = 400/(8000/2) = 0.1
Note: if the cut off frequency is in radians then the normalized frequency is
computed as wc = Wc /
- Step 2: Compute the Impulse Response h(n) of the required FIR filter using the
given Window type and the response type (lowpass, bandpass, etc). For example
given a rectangular window, order N=20, and a high pass response, the
coefficients (i.e., h[n] samples) of the filter are computed using the MATLAB
inbuilt command fir1 as
h =fir1(N, wc , 'high', boxcar(N+1));
DSP Lab Manual
Dept of ECE VITAE, HYD 21
Note: In theory we would have calculated h[n]=hd[n]w[n], where hd[n] is the
desired impulse response (low pass/ high pass,etc given by the sinc function) and
w[n] is the window coefficients. We can also plot the window shape as
stem(boxcar(N)).
Plot the frequency response of the designed filter h(n) using the freqz function and
observe the type of response (lowpass / highpass /bandpass).

Method 2:
Given the pass band (wp in radians) and Stop band edge (ws in radians) frequencies,
Pass band ripple Rp and stopband attenuation As.
- Step 1: Select the window depending on the stopband attenuation required.
Generally if As>40 dB, choose Hamming window. (Refer table )
- Step 2: Compute the order N based on the edge frequencies as
Transition bandwidth = tb=ws-wp;
N=ceil (6.6*pi/tb);
- Step 3: Compute the digital cut-off frequency Wc as
Wc=(wp+ws)/2
Now compute the normalized frequency in the range 0 to 1 for MATLAB
as
wc=Wc/pi;
Note: In step 2 if frequencies are in Hz, then obtain radian frequencies (for computation
of tb and N) as wp=2*pi*fp/fs, ws=2*pi*fstop/fs, where fp, fstop and fs are the
passband, stop band and sampling frequencies in Hz
- Step 4: Compute the Impulse Response h(n) of the required FIR filter using N,
selected window, type of response(low/high, etc) using fir1 as in step 2 of
method 1.




MATLAB IMPLEMENTATION
DSP Lab Manual
Dept of ECE VITAE, HYD 22
FIR1 Function : B = FIR1(N,Wn) designs an N'th order lowpass FIR digital filter and
returns the filter coefficients in length N+1 vector B. The cut-off frequency Wn must be
between 0 < Wn < 1.0, with 1.0 corresponding to half the sample rate. The filter B is real
and has linear phase, i.e., even symmetric coefficients obeying B(k) = B(N+2-k), k =
1,2,...,N+1.
If Wn is a two-element vector, Wn = [W1 W2], FIR1 returns an order N bandpass filter
with passband W1 < W < W2. B = FIR1(N,Wn,'high') designs a highpass filter. B =
FIR1(N,Wn,'stop') is a bandstop filter if Wn = [W1 W2]. If Wn is a multi-element vector,
Wn = [W1 W2 W3 W4 W5 ... WN], FIR1 returns an order N multiband filter with bands
0 < W < W1, W1 < W < W2, ..., WN < W < 1.FREQZ Digital filter frequency
response. [H,W] = FREQZ(B,A,N) returns the N-point complex frequency response
vector H and the N-point frequency vector W in radians/sample of the filter whose
numerator and denominator coefficients are in vectors B and A. The frequency
response is evaluated at N points equally spaced around the upper half of the unit circle.
If N isn't specified, it defaults to 512.
For FIR filter enter A=1 and B = h[n] coefficients. Appropriately choose N as 128, 256,
etc
Window Transition Width e A Min. Stop band Matlab
Name Approximate Exact values Attenuation Command

Rectangular
M
H 4

M
H 8 . 1
21db B= FIR1(N,Wn,boxcar)
Bartlett
M
H 8

M
H 1 . 6
25db B = FIR1(N,Wn,bartlett)
Hanning
M
H 8

M
H 2 . 6
44db B = FIR1(N,Wn,hanning)
Hamming
M
H 8

M
H 6 . 6
53db B= FIR1(N,W
n,
hamming)
Blackman
M
H 12

M
H 11
74db B = FIR1(N,Wn,blackman)

Program:
DSP Lab Manual
Dept of ECE VITAE, HYD 23

%Method 2: the following program gives only the design of the FIR filter- for
implementation continue with the next program (after h[n])
%input data to be given: Passband & Stopband frequency
% Data given: Passband ripple & stopband attenuation As. If As>40 dB, Choose
hamming

clear
wpa=input('Enter passband edge frequency in Hz');
wsa= input('Enter stopband edge frequency in Hz');
ws1= input('Enter sampling frequency in Hz');
%Calculate transmission BW,Transition band tb,order of the filter
wpd=2*pi*wpa/ws1;
wsd=2*pi*wsa/ws1;
tb=wsd-wpd;
N=ceil(6.6*pi/tb)
wc=(wsd+wpd)/2;
%compute the normalized cut off frequency
wc=wc/pi;
%calculate & plot the window
hw=hamming(N+1);
stem(hw);
title('Fir filter window sequence- hamming window');
%find h(n) using FIR
h=fir1(N,wc,hamming(N+1));
%plot the frequency response
figure(2);
[m,w]=freqz(h,1,128);
mag=20*log10(abs(m));
plot(ws1*w/(2*pi),mag);
title('Fir filter frequency response');
DSP Lab Manual
Dept of ECE VITAE, HYD 24
grid;

%generate simulated input of 50, 300 & 200 Hz, each of 30 points
n=1:30;
f1=50;f2=300;f3=200;fs=1000;
x=[];
x1=sin(2*pi*n*f1/fs);
x2=sin(2*pi*n*f2/fs);
x3=sin(2*pi*n*f3/fs);
x=[x1 x2 x3];
subplot(2,1,1);
stem(x);
title('input');
%generate o/p
%y=conv(h,x);
y=filter(h,1,x);
subplot(2,1,2);
stem(y);
title('output');

Result:
Enter passband edge frequency in Hz100
Enter stopband edge frequency in Hz200
Enter sampling frequency in Hz1000
N = 33
Plots are as in Fig.11.1 and 11.2

Inference:
Notice the maximum stopband attenuation of 53 dB from plot 11.2

%Design and implementation of FIR filter Method 1
DSP Lab Manual
Dept of ECE VITAE, HYD 25

%generate filter coefficients for the given %order & cutoff Say N=33, fc=150Hz,
%fs=1000 Hz, Hamming window
h=fir1(33, 150/(1000/2),hamming(34));
%generate simulated input of 50, 300 & 200 Hz, each of 30 points
n=1:30;
f1=50;f2=300;f3=200;fs=1000;
x=[];
x1=sin(2*pi*n*f1/fs);
x2=sin(2*pi*n*f2/fs);
x3=sin(2*pi*n*f3/fs);
x=[x1 x2 x3];
subplot(2,1,1);
stem(x);
title('input');
%generate o/p
%y=conv(h,x);
y=filter(h,1,x);
subplot(2,1,2);
stem(y);
title('output');

Result:
Plots are in Fig.11.3 & 11.4
Notice that freqs below 150 Hz are passed & above 150 are cutoff

DSP Lab Manual
Dept of ECE VITAE, HYD 26

Fig.11.1 Fig.11.2

Fig.11.3(using filter command) Fig.11.4 (using conv command)


Fig.11.5 Freqs f1=150;f2=300;f3=170;fs=1000;

FIR filter design using Kaiser window:

DSP Lab Manual
Dept of ECE VITAE, HYD 27
disp('FIR filter design using Kaiser window');
M = input ('enter the length of the filter = ');
beta= input ('enter the value of beta = ');
Wc = input ('enter the digital cutoff frequency');
Wn= kaiser(M,beta);
disp('FIR Kaiser window coefficients');
disp(Wn);
hn = fir1(M-1,Wc,Wn);
disp('the unit sample response of FIR filter is hn=');
disp(hn);
freqz(hn,1,512);
grid on;
xlabel('normalized frequency');
ylabel('gain in db');
title('freq response of FIR filter');

Result:
FIR filter design using Kaiser window
enter the length of the filter = 30
enter the value of beta = 1.2
enter the digital cutoff frequency.3
FIR Kaiser window coefficients
0.7175 0.7523 0.7854 0.8166 0.8457 0.8727 0.8973 0.9195
0.9392 0.9563 0.9706 0.9822 0.9909 0.9967 0.9996 0.9996
0.9967 0.9909 0.9822 0.9706 0.9563 0.9392 0.9195 0.8973
0.8727 0.8457 0.8166 0.7854 0.7523 0.7175

the unit sample response of FIR filter is hn=
Columns 1 through 5
0.0141 0.0028 -0.0142 -0.0224 -0.0117
Columns 6 through 10
DSP Lab Manual
Dept of ECE VITAE, HYD 28
0.0133 0.0333 0.0277 -0.0072 -0.0495
Columns 11 through 15
-0.0614 -0.0140 0.0895 0.2097 0.2900
Columns 16 through 20
0.2900 0.2097 0.0895 -0.0140 -0.0614
Columns 21 through 25
-0.0495 -0.0072 0.0277 0.0333 0.0133
Columns 26 through 30
-0.0117 -0.0224 -0.0142 0.0028 0.0141



Fig.11.6.Response of FIR filter designed using Kaiser window




DSP Lab Manual
Dept of ECE VITAE, HYD 29
EXPERIMENT NO 8,9: Design and implementation of IIR filter to
meet given specifications

Aim: To design and implement an IIR filter for given specifications.

Theory:
There are two methods of stating the specifications as illustrated in previous program. In
the first program, the given specifications are directly converted to digital form and the
designed filter is also implemented. In the last two programs the butterworth and
chebyshev filters are designed using bilinear transformation (for theory verification).
Method I: Given the order N, cutoff frequency fc, sampling frequency fs and the IIR
filter type (butterworth, cheby1, cheby2).
- Step 1: Compute the digital cut-off frequency Wc (in the range - < Wc < , with
corresponding to fs/2) for fc and fs in Hz. For example let fc=400Hz, fs=8000Hz
Wc = 2** fc / fs = 2* * 400/8000 = 0.1* radians
For MATLAB the Normalized cut-off frequency is in the range 0 and 1, where 1
corresponds to fs/2 (i.e.,fmax)). Hence to use the MATLAB commands
wc = fc / (fs/2) = 400/(8000/2) = 0.1
Note: if the cut off frequency is in radians then the normalized frequency is computed
as wc = Wc /
- Step 2: Compute the Impulse Response [b,a] coefficients of the required IIR filter
and the response type (lowpass, bandpass, etc) using the appropriate butter, cheby1,
cheby2 command. For example given a butterworth filter, order N=2, and a high pass
response, the coefficients [b,a] of the filter are computed using the MATLAB inbuilt
command butter as [b,a] =butter(N, wc , 'high');
Method 2:
Given the pass band (Wp in radians) and Stop band edge (Ws in radians) frequencies,
Pass band ripple Rp and stopband attenuation As.
- Step 1: Since the frequencies are in radians divide by to obtain normalized
frequencies to get wp=Wp/pi and ws=Ws/pi
DSP Lab Manual
Dept of ECE VITAE, HYD 30
If the frequencies are in Hz (note: in this case the sampling frequency should be
given), then obtain normalized frequencies as wp=fp/(fs/2), ws=fstop/(fs/2),
where fp, fstop and fs are the passband, stop band and sampling frequencies in Hz
- Step 2: Compute the order and cut off frequency as
[N, wc] = BUTTORD(wp, ws, Rp, Rs)
- Step 3: Compute the Impulse Response [b,a] coefficients of the required IIR filter
and the response type as [b,a] =butter(N, wc , 'high');

IMPLEMENTATION OF THE IIR FILTER
1. Once the coefficients of the IIR filter [b,a] are obtained, the next step is to
simulate an input sequence x[n], say input of 100, 200 & 400 Hz (with sampling
frequency of fs), each of 20/30 points. Choose the frequencies such that they are
>, < and = to fc.
2. Filter the input sequence x[n] with Impulse Response, to obtain the output of the
filter y[n] using the filter command.
3. Infer the working of the filter (low pass/ high pass, etc).

MATLAB IMPLEMENTATION
BUTTORD Butterworth filter order selection.
[N, Wn] = BUTTORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital
Butterworth filter that loses no more than Rp dB in the passband and has at least Rs dB of
attenuation in the stopband. Wp and Ws are the passband and stopband edge frequencies,
normalized from 0 to 1 (where 1 corresponds to pi radians/sample). For example,
Lowpass: Wp = .1, Ws = .2 Highpass: Wp = .2, Ws = .1
Bandpass: Wp = [.2 .7], Ws = [.1 .8] Bandstop: Wp = [.1 .8], Ws = [.2 .7]
BUTTORD also returns Wn, the Butterworth natural frequency (or, the "3 dB
frequency") to use with BUTTER to achieve the specifications.
[N, Wn] = BUTTORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in
which case Wp and Ws are in radians/second.
When Rp is chosen as 3 dB, the Wn in BUTTER is equal to Wp in BUTTORD.
BUTTER Butterworth digital and analog filter design.
DSP Lab Manual
Dept of ECE VITAE, HYD 31
[B,A] = BUTTER(N,Wn) designs an Nth order lowpass digital Butterworth filter and
returns the filter coefficients in length N+1 vectors B (numerator) and A (denominator).
The coefficients are listed in descending powers of z. The cutoff frequency Wn must be
0.0 < Wn < 1.0, with 1.0 corresponding to half the sample rate. If Wn is a two-element
vector, Wn = [W1 W2], BUTTER returns an order 2N bandpass filter with passband W1
< W < W2. [B,A] = BUTTER(N,Wn,'high') designs a highpass filter. [B,A] =
BUTTER(N,Wn,'stop') is a bandstop filter if Wn = [W1 W2].
BUTTER(N,Wn,'s'), BUTTER(N,Wn,'high','s') and BUTTER(N,Wn,'stop','s') design
analog Butterworth filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.

Program (Design & implementation)
%generate filter coefficients for the given %order & cutoff %Say N=2, fc=150Hz,
%fs=1000 Hz, butterworth filter

[b,a]=butter(2, 150/(1000/2));
%generate simulated input of 100, 300 & 170 Hz, each of 30 points
n=1:30;
f1=100;f2=300;f3=170;fs=1000;
x=[];
x1=sin(2*pi*n*f1/fs);
x2=sin(2*pi*n*f2/fs);
x3=sin(2*pi*n*f3/fs);
x=[x1 x2 x3];
subplot(2,1,1);
stem(x);
title('input');
%generate o/p
y=filter(b,a,x);
subplot(2,1,2);
stem(y);
title('output');
DSP Lab Manual
Dept of ECE VITAE, HYD 32
Result:
Plot is in Fig. 12.1, which shows that 100 Hz is passed, while 300 is cutoff and 170
has slight attenuation.

Note: If fp,fstp,fs, rp,As are given then use
[N,wc]=buttord(2*fp/fs,2*fstp/fs,rp,As)
[b,a]=butter(N,wc);
If wp & ws are in radians
[N,wc]=buttord(wp/pi,ws/pi,rp,As)
[b,a]=butter(N,wc);
If wc is in radians & N is given
[b,a]=butter(N,wc/pi);
For a bandpass output
wc=[150/(1000/2) 250/(1000/2)];
[b,a]=butter(4, wc);
Plot is in Fig.12.2 where only 170 is passed, while 100 & 300 are cutoff.

Fig.12.1 Low pass IIR filter(butterworth) output
DSP Lab Manual
Dept of ECE VITAE, HYD 33

Fig.12.2 IIR output for bandpass (150-250 Hz)
Programs for designing of IIR filters (for theory practice):
% Butterworth filter: Given data: rp=1, rs=40, w1=800, %w2=1200,ws=3600;
rp=1, rs=40, w1=800, w2=1200,ws=3600;

% Analog frequency
aw1=2*pi*w1/ws;
aw2=2*pi*w2/ws;

% Prewrapped frequency
pw1 = 2*tan(aw1/2);
pw2 = 2*tan(aw2/2);

%Calculate order and cutoff freq
[n,wc]= buttord (pw1,pw2,rp,rs,'s');
% analog filter transfer
DSP Lab Manual
Dept of ECE VITAE, HYD 34
[b,a] = butter(n,wc,'s');

%obtaining the digital filter using bilinear transformation
fs=1;
[num,den]= bilinear(b,a,fs);

%plot the frequency response
[mag,freq1]=freqz(num,den,128);
freq=freq1*ws/(2*pi);
m = 20*log10(abs(mag));
plot(freq,m);
grid;

Result: rp = 1 rs = 40 w1 = 800 w2 = 1200

Fig. 12.2 BUTTERWORTH FILTER








DSP Lab Manual
Dept of ECE VITAE, HYD 35
To design a chebyshev filter for given specifications
%Given data
rp=1,rs=40,w1=800,w2=1200,ws=3600
%Analog frequencies
aw1= 2*pi*w1/ws;
aw2=2*pi*w2/ws;
% Prewrapped frequency assuming T=1/fs
pw1 = 2*tan(aw1/2);
pw2 = 2*tan(aw2/2);
[n,wc]= cheb1ord (pw1,pw2,rp,rs,'s');
[b,a] = cheby1(n,rp,wc,'s');
%obtaining the digital filter using bilinear transformation
fs=1;
[num,den]= bilinear(b,a,fs);
%plot the frequency response
[mag,freq1]=freqz(num,den,128);
freq=freq1*ws/(2*pi);
m = 20*log10(abs(mag));
plot(freq,m);grid;

Result: rp = 1 rs = 40 w1 = 800 w2 = 1200 ws = 360








Fig.12.3 CHEBYSHEV FILTER
DSP Lab Manual
Dept of ECE VITAE, HYD 36
EXPERIMENT NO 10: Generation of sinusoidal wave using recursive difference
equation

Aim: To generate sinusoidal signal using recursive difference equation

Theory:
There exists different techniques to generate a sine wave on a DSP processor.Using a lookup table,
interpolation, polynomials, or pulse width modulation are some of these techniques utilized to generate a
sine wave. When a slightly sufficient processing power is considered, it is possible to utilize another
technique which makes use of an IIR filter.In this technique, a second order IIR filter as shown in Figure 1
is designed to be marginally stable which is an undesirable situation for a normal filtering operation. For
this second order filter to be marginally stable, its poles are located in the unit circle. After choosing the
suitable filter coefficients for the filter to be marginally stable, a unit impulse is applied to the filter as an
input at time t = 0, and then the input is disconnected. Then the filter starts to oscillate with a fixed
frequency.


The difference equation of the second order filter shown in Figure 1 will be:
DSP Lab Manual
Dept of ECE VITAE, HYD 37

Where F0 is the frequency, Fs is the sampling frequency and A is the amplitude of the
sine wave.

Matlab Program

% Generation of sine wave using recursive difference equation or IIR filter
%fs = sampling rate
% t = time in sec
%f0 = frequency
% A = amplitude
A = 2;
t=0.1;
fs = 5000;
f0=50;
length = fs*t;
y = zeros(1,length);
impulse = zeros(1,length);
impulse(1) = 1;
% frequency coefficients
% difference equation of form y[n]= -a1 y[n-1] -a2 y[n-2] + b0 impulse[n]
DSP Lab Manual
Dept of ECE VITAE, HYD 38
% a1 = -2cos(2*pi*f0/fs), a2= 1, b0 = Asin(2*pi*f0/fs)
a1 = -2*cos(2*pi*f0/fs)
a2 = 1;
b0 = A*sin(2*pi*f0/fs)
y(1)= 0;
y(2)= b0;
for i=3:length
y(i)= b0* impulse(i)- a1*y(i-1) - a2* y(i-2);
end
plot (y);
title('Sinusoidal waveform')
xlabel('samples n');
ylabel('y(n)');

Result :



DSP Lab Manual
Dept of ECE VITAE, HYD 39
Experiment No. 11 Generation of DTMF signals

Therory: Dual-tone Multi-Frequency (DTMF) signaling is the basis for voice
communications control and is widely used worldwide in modern telephony to dial
numbers and configure switchboards. It is also used in systems such as in voice mail,
electronic mail and telephone banking.

A DTMF signal consists of the sum of two sinusoids - or tones - with frequencies taken
from two mutually exclusive groups. These frequencies were chosen to prevent any
harmonics from being incorrectly detected by the receiver as some other DTMF
frequency. Each pair of tones contains one frequency of the low group (697 Hz, 770 Hz,
852 Hz, 941 Hz) and one frequency of the high group (1209 Hz, 1336 Hz, 1477Hz) and
represents a unique symbol. The frequencies allocated to the push-buttons of the
telephone pad are shown below:










We will right the program to generate and visualize the DTMF tones for all 12 Symbols.
Also we will estimate its energy content using Gortzets Algorithm
The minimum duration of a DTMF signal defined by the ITU standard is 40 ms.
Therefore, there are at most 0.04 x 8000 = 320 samples available for estimation and
detection. The DTMF decoder needs to estimate the frequencies contained in these short
signals.

1209Hz 1336Hz 1477 Hz
697Hz

1
ABC
2
DEF
3
770 Hz
GHI
4
JKL
5
MNO
6
852Hz
PQRS
7
TUV
8
WXYZ
9
941 Hz

*
0 #
DSP Lab Manual
Dept of ECE VITAE, HYD 40
One common approach to this estimation problem is to compute the Discrete-Time
Fourier Transform (DFT) samples close to the seven fundamental tones. For a DFT-based
solution, it has been shown that using 205 samples in the frequency domain minimizes
the error between the original frequencies and the points at which the DFT is estimated.

At this point we could use the Fast Fourier Transform (FFT) algorithm to calculate the
DFT. However, the popularity of the Goertzel algorithm in this context lies in the small
number of points at which the DFT is estimated. In this case, the Goertzel algorithm is
more efficient than the FFT algorithm.

Plot Goertzel's DFT magnitude estimate of each tone on a grid corresponding to the
telephone pad.

MATLAB Program

% generating all 12 frequencies
symbol = {'1','2','3','4','5','6','7','8','9','*','0','#'};
lfg = [697 770 852 941]; % Low frequency group
hfg = [1209 1336 1477]; % High frequency group
f = [];
for c=1:4,
for r=1:3,
f = [ f [lfg(c);hfg(r)] ];
end
end
f'
% Generate the DTMF tones
Fs = 8000; % Sampling frequency 8 kHz
N = 800; % Tones of 100 ms
t = (0:N-1)/Fs; % 800 samples at Fs
pit = 2*pi*t;
DSP Lab Manual
Dept of ECE VITAE, HYD 41

tones = zeros(N,size(f,2));
for toneChoice=1:12,
% Generate tone
tones(:,toneChoice) = sum(sin(f(:,toneChoice)*pit))';
% Plot tone
subplot(4,3,toneChoice),plot(t*1e3,tones(:,toneChoice));
title(['Symbol "', symbol{toneChoice},'":
[',num2str(f(1,toneChoice)),',',num2str(f(2,toneChoice)),']'])
set(gca, 'Xlim', [0 25]);
ylabel('Amplitude');
if toneChoice>9, xlabel('Time (ms)'); end
end
set(gcf, 'Color', [1 1 1], 'Position', [1 1 1280 1024])
annotation(gcf,'textbox', 'Position',[0.38 0.96 0.45 0.026],...
'EdgeColor',[1 1 1],...
'String', '\bf Time response of each tone of the telephone pad', ...
'FitHeightToText', 'on');
% estimation of DTMF tone using Gortzel's Algorithm
Nt = 205;
original_f = [lfg(:);hfg(:)] % Original frequencies
k = round(original_f/Fs*Nt); % Indices of the DFT
estim_f = round(k*Fs/Nt) % Frequencies at which the DFT is estimated
tones = tones(1:205,:);
figure,
for toneChoice=1:12,
% Select tone
tone=tones(:,toneChoice);
% Estimate DFT using Goertzel
ydft(:,toneChoice) = goertzel(tone,k+1); % Goertzel use 1-based indexing
% Plot magnitude of the DFT
DSP Lab Manual
Dept of ECE VITAE, HYD 42
subplot(4,3,toneChoice),stem(estim_f,abs(ydft(:,toneChoice)));
title(['Symbol "', symbol{toneChoice},'":
[',num2str(f(1,toneChoice)),',',num2str(f(2,toneChoice)),']'])
set(gca, 'XTick', estim_f, 'XTickLabel', estim_f, 'Xlim', [650 1550]);
ylabel('DFT Magnitude');
if toneChoice>9, xlabel('Frequency (Hz)'); end
end
set(gcf, 'Color', [1 1 1], 'Position', [1 1 1280 1024])
annotation(gcf,'textbox', 'Position',[0.28 0.96 0.45 0.026],...
'EdgeColor',[1 1 1],...
'String', '\bf Estimation of the frequencies contained in each tone of the telephone pad
using Goertzel', ...
'FitHeightToText','on');


Output:

DSP Lab Manual
Dept of ECE VITAE, HYD 43
Experiment No. 12, 13, 14: Implementation of Interpolation, decimation
and I/D sampling rate converters

Theory:
Multirate : Changing the Sampling Rate of the Discrete Time Signal.The process of
converting a signal from a given rate to a different rate is called sampling rate
conversion.
Systems that employ multiple sampling rates in the processing of digital signals are
called multirate digital signal processing systems.

Can be accomplished in two ways:


Adv: New sampling rate can be arbitrarily selected
Disadv: Signal distortion is introduced by
- D/A converter in signal reconstruction
- Quantization effects in A/D converter

Changing the sampling rate in digital domain --Multirate
Fundamental operations in multirate signal processing are
1) Downsampling (Decimation)
2) Upsampling(Interpolation )

Decimation is the process of decreasing the sampling rate by a factor of M i.e. from Fs
to Fs / M
DSP Lab Manual
Dept of ECE VITAE, HYD 44
Down sampling : by a factor of M is achieved by discarding M-1 samples for every M
samples.

This combined operation of filtering and downsampling is called as decimation.

DSP Lab Manual
Dept of ECE VITAE, HYD 45


The rate compressor reduces the sampling rate from F
s
to F
s
/ M
To prevent aliasing at lower rate, digital filter is used to band limit the i/p signal to less
than F
s
/2M. (new folding frequency).
Sampling rate reduction is achieved by discarding M-1 samples for every M samples of
filtered signal W(n).



INTERPOLATION
DSP Lab Manual
Dept of ECE VITAE, HYD 46
Process of increasing the sampling rate of the signal by a factor of L i.e. from F
s
to LF
s

Upsampling by a factor L means inserting L-1 zeros between two samples



DSP Lab Manual
Dept of ECE VITAE, HYD 47



In matlab we can use function resample() to achieve interpolation as well as decimation.

MATLAB program:
% % m-file to illustrate simple interpolation and
% decimation operations
% File name:
%
Fs=input('Enter Sampling Frequency:'); % sampling frequency
I= input('interpolation factor:');
A=1.5; % relative amplitudes
B=1;
f1=50; % signal frequencies
f2=100;
DSP Lab Manual
Dept of ECE VITAE, HYD 48
t=0:1/Fs:1; % time vector
x=A*cos(2*pi*f1*t)+B*cos(2*pi*f2*t); % generate signal
y=resample(x,I,1); % interpolate signal by 4
stem(x(1:100)) % plot original signal
xlabel('Discrete time, nT ')
ylabel('Input signal level')
figure
stem(y(1:400)) % plot interpolated signal.

xlabel('Discrete time 4 X nT')
ylabel('Interpolated output signal level')
D=input('Enter the decimation factor:');
y1=resample(x,1,D);
figure
stem(y1(1:50)) % plot decimated signal.
xlabel('Discrete time nT/2')
ylabel('Decimated output signal level')

Result
>> decimation
Enter Sampling Frequency:1000
interpolation factor:4
Enter the decimation factor:2
DSP Lab Manual
Dept of ECE VITAE, HYD 49

You might also like