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

JSS Mahavidyapeetha, Mysuru

JSS Academy of Technical Education,


Bengaluru-560060

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING
DIGITAL SIGNAL PROCESSING LAB
(15ECL57)
Prepared By:
Mr. Sathish Shet K, Asst. Prof.
Mrs. Sheela S N, Asst. Prof.
Mr. Parameshappa G, Astt. Prof.
Mrs. Suguna G C, Asst. Prof.
Mrs. Mamatha S, Programme

Affiliated to Visvesvaraya Technological University Jnana Sangama, Machhe, Belagavi, Karnataka-590018

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING JSS


ACADEMY OF TECHNICAL EDUCATION
JSS Campus, Dr. Vishnuvardhana Road, Bengaluru - 560060.
VISION of the Institute: MISSION of the Institute:
To be among the finest Institutions providing M1: Strive towards Excellence in teaching–learning
EngineeringandManagementEducation process and nurture personality development.
empowered with research, innovation and M2: Encourage Research, Innovation &
Entrepreneurship. Entrepreneurship.
M3: Train to uphold highest ethical standards in all
activities.
VISION of ECE Department: MISSION of ECE Department:
Enable the students to achieve academic M1: Orient the students to meet global challenges in the
excellence at par with premier institutes and to field of Electronics and Communication
meet the requirements of industry and research Engineering with state-of-the-art facilities and
in the field of Electronics and Communication good teaching- learning process.
Engineering. M2: Impart knowledge in the emerging areas through
Industry Institute-interaction, seminars, workshops
and conferences.
M3: Provide a strong foundation in core subjects to
enable the students for continuous learning and
research.
M4: Facilitate students for soft skills and professional
ethics.
Programme Educational Objectives (PEOs):
PEOs are broad statements that describe the career and professional accomplishments that the
programme is preparing the graduates to achieve.

PEO1: Graduates will be able to apply fundamental Engineering, Scientific & Mathematical concepts to
solve practical problems.

PEO2: Graduates apply the knowledge gained to solve complex problems in emerging technologies
of Electronics Engineering and allied areas.

PEO3: Graduates develop innovative ideas leading to research and product development.

PEO4: Graduates exhibit high professional ethics with human values and social responsibilities.

Program Specific Outcomes (PSO’s)


PSO1:
Solve the Engineering problems of Electronics and Communication Engineering in VLSI design, Embedded
Systems, Communication Engineering, Power Electronics and Control Systems.

PSO2:
Demonstrate the programming skills using assembly and high level languages to solve Engineering problems.

PSO3:
Design, realize and validate various Electronic systems.
Digital Signal Processing Lab (15ECL57) V Semester

Programme outcomes
Graduates Attributes (GAs) form a set of individually assessable outcomes that are the components
indicative of the graduate’s potential to acquire competence to practice at the appropriate level. The
GAs are exemplars of the attributes expected of a graduate from an accredited programme. The
Graduate Attributes of the NBA are as following:

1.Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,


and an Engineering specialization to the solution of complex engineering problems.

2.Problem Analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.

3.Design/development of Solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.

4. Conduct Investigations of Complex Problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

5. Modern Tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.

6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal, and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

7. Environment and Sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.

9. Individual and Team Work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multi disciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

11. Project Management and Finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.

12. Life-long Learning: Recognize the need for, and have the preparation and ability to
engage in dependent and life-long learning in the broadest context of technological change.
Dept. of ECE, JSSATE, Bengaluru-60 Page 3
Digital Signal Processing Lab (15ECL57) V Semester

List of Experiments
DSP Lab
B.E., V Semester, EC/TC
[As per Choice Based Credit System (CBCS) scheme]

Subject Code 15ECL57 IA Marks 20


Number of Lecture 01Hr Tutorial (Instructions) Exam Marks 80
Hours/Week + 02 Hours Laboratory=03

Exam Hours 03
CREDITS – 02
Laboratory Experiments

Following Experiments to be done using MATLAB / SCILAB / OCTAVE or equivalent:

1. Verification of sampling theorem.


2. Linear and circular convolution of two given sequences, Commutative, distributive and
associative property of convolution.
3. Auto and cross correlation of two sequences and verification of their properties.
4. Solving a given difference equation.
5. Computation of N point DFT of a given sequence and to plot magnitude and phase spectrum
(using DFT equation and verify it by built-in routine).
6. (i) Verification of DFT properties (like Linearity and Parsevals theorem, etc.)
(ii) DFT computation of square pulse and Sinc function etc.
7. Design and implementation of FIR filter to meet given specifications (using different
window techniques).
8. Design and implementation of IIR filter to meet given specifications.

Following Experiments to be done using DSP kit

9. Linear convolution of two sequences


10. Circular convolution of two sequences
11. N-point DFT of a given sequence
12. Impulse response of first order and second order system
13. Implementation of FIR filter

Conduct of Practical Examination:


1. All laboratory experiments are to be included for practical examination.
2. Strictly follow the instructions as printed on the cover page of answer script for breakup of
marks.
3. Change of experiment is allowed only once and Marks allotted to the procedure part to be
made zero.

Dept. of ECE, JSSATE, Bengaluru-60 Page 4


Digital Signal Processing Lab (15ECL57) V Semester

Course outcomes of DSP LAB


Students must be able to

COs DSP LAB Bloom’s Level


C307.1 Make use of Nyquist criteria to verify sampling process. L3
C307.2 Analyze the concept of convolution, correlation and verify its properties. L4
C307.3 Evaluate N - point DFT of the given signal & verify its properties. L5
C307.4 Design & implement Digital Filters to meet given specifications. L6

CO-PO Mapping:

POs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
COs
C307.1 3 3 - - 3 - - - - - - -
C307.2 3 3 - - 3 - - - - - - -
C307.3 3 3 2 - 3 - - - - - - -
C307.4 3 3 3 - 3 - - - - - - -
Average 3 3 2.5 - 3 - - - - - - -

CO-PSO Mapping:

COs PSO1 PSO2 PSO3


C307.1 2 2 -
C307.2 2 2 -
C307.3 2 2 -
C307.4 2 2 -
Average 2 2 -

Name & Signature of faculty: 1. Mrs. Suguna G C


2. Mr. Parameshappa G
3. Mr. Sathish Shet K
4. Mrs Sheela S N

Name & Reviewer Signature: 1. Dr. Siddesh G K


2. Mrs Veeramma Yatnalli
3. Mrs Shuba B

Signature of HOD

Dept. of ECE, JSSATE, Bengaluru-60 Page 5


Digital Signal Processing Lab (15ECL57) V Semester

Justification for rationale of CO and PO mapping:

COs POs Level Justification


Basic knowledge of mathematics, engineering fundamentals are required to
PO1 3
understand Nyquist criteria and sampling process.
C307.1 To identify and analyze concept of sampling, oversampling and under sampling
PO2 3
using concepts of Mathematics and engineering science.
PO5 3 Use Modern Tool and CCS for analyzing Sampling Process and its Limitations.
Basic knowledge of mathematics, engineering fundamentals are required to
PO1 3
understand the concept of convolution, correlation and its properties.
C307.2 Analyze Linear convolution, circular convolution, Auto correlation cross correlation
PO2 3
and its properties using principles of mathematics and Engineering science.
PO5 3 Use Modern Tool and CCS for analyzing Convolutions and its Limitations.
Basic knowledge of mathematics, engineering fundamentals are required to
PO1 3
understand FFT using MATLAB
C307.3 Analyze DITFFT and DIFFFT algorithms using research literature to reach
PO2 3
substantial conclusion about computational complexity.
PO3 2 Design DITFFT and DIFFFT algorithms for the specified inputs.
PO5 3 Use Modern Tool and CCS for analyzing FFT and its Limitations
Basic knowledge of mathematics, engineering fundamentals are required to design
PO1 3
Digital filters.
Analyze IIR and FIR filter based on research literature using first principles of
PO2 3
C307.4 mathematics & Engineering science.
Design Filters for the Given specification to meet the specified needs for societal
PO3 3
and environmental consideration..
PO5 3 Use Modern Tool and CCS for analyzing Digital Filters and its Limitations

Justification for rationale of CO and PSO mapping:

COs PSOs Level Justification


Applying the basic knowledge of signal processing, design a code using MATLAB
PSO1 2
to solve any Engineering problems.
C307.1
To identify and analyze different signals in Engineering and communication field
PSO2 2
and demonstrate using a MATLAB code and TMS320DSKC6713 Processor.
To apply the concepts of Convolution and correlation in the field of core areas like
PSO1 2 signal processing, Embedded, power electronics, controls to design a MATLAB
C307.2 code and TMS320DSKC6713 Processor
To identify and analyze different signals in Engineering and communication field
PSO2 2
and demonstrate using a MATLAB code.
PSO1 2 Applying the concepts of FFT to analyze and to solve any Engineering problems.
C307.3 To identify and analyze different signals in Engineering and communication field
PSO2 2
and demonstrate using a MATLAB code & TMS320DSKC6713 Processor
To design Digital filters for a specific application in core areas like Signal
PSO1 2
Processing and Control Systems.
C307.4
To write a Matlab code to simulate filter design and realize Filters using
PSO2 2
TMS320DSKC6713

Name & Signature of faculty: 1. Mrs. Suguna G C


2. Mr. Parameshappa G
3. Mr. Sathish Shet K
4. Mrs Sheela S N

Dept. of ECE, JSSATE, Bengaluru-60 Page 6


Digital Signal Processing Lab (15ECL57) V Semester

INDEX

Sl. Page No.


EXPERIMENTS NAME
No.
Verification of sampling theorem.
1 to 3
1

a) Linear convolution of two given sequences, Commutative, distributive and 4 to 9


associative property of convolution.

2 b) Circular convolution of two given sequences, Commutative, distributive and


associative property of convolution. 10 to 17

a) Auto correlation of two sequences and verification of their properties. 18 to 22

3 b) Cross correlation of two sequences and verification of their properties. 23 to 26

Solving a given Difference Equation. 27 to 28


4

Computation of N point DFT of a given sequence and to plot magnitude and 29 to 30


phase spectrum (using DFT equation and verify it by built-in routine).
5

a) Verification of DFT properties (like Linearity and Parsevals theorem, etc.) 31 to 33


6
b) DFT computation of square pulse and Sinc function etc. 34 to 37

Design and implementation of FIR filter to meet given specifications (using 38 to 40


7 different window techniques).

Design and implementation of IIR filter to meet given specifications. 41 to 45


8

Procedure to Setup Emulator 46 to 55

Dept. of ECE, JSSATE, Bengaluru-60 Page 7


Digital Signal Processing Lab (15ECL57) V Semester

Linear convolution of two sequences 56 to 63


10

Circular convolution of two sequences 64 to 65


11

N-point DFT of a given sequence 66 to 67


12

Impulse response of first order and second order system 68 to 70


13

Implementation of FIR filter 71 to 76


14

Viva Question 77 to 82

Question Bank 83 to 84

Related to MATLAB 85 to 99

Experiment 1: Write a MATLAB code for Verification of Sampling theorem.

The Sampling theorem is a fundamental bridge between continuous-time signals (often called
"analog signals") and discrete-time signals (often called "digital signals").
Sampling: Is the process of converting a continuous time signal into a discrete time signal. It is
the first step in conversion from analog signal to digital signal.
When the band limit is too high (or there is no band limit), the reconstruction exhibits
imperfections known as aliasing. Modern statements of the theorem are sometimes careful to
explicitly state that x(t) must contain no sinusoidal component at exactly frequency B, or
that B must be strictly less than ½ the sample rate. The two thresholds, 2B and fs/2 are respectively
called the Nyquist rate and Nyquist frequency.

Dept. of ECE, JSSATE, Bengaluru-60 Page 8


Digital Signal Processing Lab (15ECL57) V Semester

Sampling theorem states that “Exact reconstruction of a continuous time base-band signal from
its samples is possible, if the signal is band-limited and the sampling frequency is greater than
twice the highest frequency component (fm) present in the signal ”. Sampling ƒs ≥ 2ƒm
Oversampling is the process of sampling a signal with a sampling frequency significantly
higher than twice the bandwidth or highest frequency of the signal being sampled. Oversampling
helps avoid aliasing, improves resolution and reduces noise. ie, Over Sampling ƒs >> 2ƒm
Undersampling is a technique where one samples a bandpass filtered signal at a sample
rate below its Nyquist rate (twice the upper cut-off frequency), but is still able to reconstruct the
signal. ie, Under Sampling ƒs ≤ 2ƒm

Program:

clc;
clear;

% Plot the Original Signal


t=[0:0.001:1];
f=10;
x=sin(2*pi*f*t);
figure;
subplot(4,2,[1,2]);
plot(t,x);
title(„ORIGINAL SIGNAL‟);
xlabel(„Time‟);
ylabel(„Amplitude‟);

% Sampling at frequency Fs>=2f


Fs=50;

Dept. of ECE, JSSATE, Bengaluru-60 Page 9


Digital Signal Processing Lab (15ECL57) V Semester

Ts=1/Fs;
n=t/Ts;
m=min(n):max(n);
x1=sin(2*pi*f*m*Ts);
subplot(4,2,3);
stem(m,x1);
title(„SAMPLED SIGNAL Fs>=2f‟);
xlabel(„n‟);
ylabel(„x1(n)‟);

% Reconstruction of Sampled Signal


tt=m*Ts;
dt=0.001;
tt1=min(tt):dt:max(tt);
xa=spline(tt,x1,tt1);
subplot(4,2,4);
plot(tt1,xa);
title(„RECONSTRUCTED SAMPLED SIGNAL‟);
xlabel(„Time‟);
ylabel(„Amplitude‟);

% Over Sampling at frequency Fs>>2f


Fs=200;
Ts=1/Fs;
n=t/Ts;
m=min(n):max(n);
x1=sin(2*pi*f*m*Ts);
subplot(4,2,5);
stem(m,x1);
title(„SAMPLED SIGNAL Fs>>2f‟);
xlabel(„n‟);
ylabel(„x1(n)‟);

% Reconstruction of Oversampled Signal


tt=m*Ts;
dt=0.001;
tt1=min(tt):dt:max(tt);
xa=spline(tt,x1,tt1);
subplot(4,2,6);
plot(tt1,xa);
title(„RECONSTRUCTED OVERSAMPLED SIGNAL‟);
xlabel(„Time‟);
ylabel(„Amplitude‟);

% Under Sampling at frequency Fs<=2f


Fs=10;
Ts=1/Fs;
n=t/Ts;
m=min(n):max(n);
x1=sin(2*pi*f*m*Ts);
subplot(4,2,7);
stem(m,x1);
title(„SAMPLED SIGNAL Fs<=2f‟);
xlabel(„n‟);
ylabel(„x1(n)‟);
Dept. of ECE, JSSATE, Bengaluru-60 Page 10
Digital Signal Processing Lab (15ECL57) V Semester

% Reconstruction of Under Sampled Signal


tt=m*Ts;
dt=0.001;
tt1=min(tt):dt:max(tt);
xa=spline(tt,x1,tt1);
subplot(4,2,8);
plot(tt1,xa);
title(„RECONSTRUCTED UNDERSAMPLED SIGNAL‟);
xlabel(„Time‟);
ylabel(„Amplitude‟);

Conclusion: sampling theorem is verified for all the three conditions.

Applications:
1. Audio sampling
2. Speech sampling
3. Video sampling

Dept. of ECE, JSSATE, Bengaluru-60 Page 11


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 2: Write a MATLAB code to compute Linear and Circular


Convolution of two given sequences, Commutative, distributive and associative
property of convolution.

2. a. Linear Convolution

Theory: Convolution is an integral concatenation of two signals. It has many applications in


numerous areas of signal processing. The most popular application is the determination of the
output signal of a linear time-invariant system by convolving the input signal with the impulse
response of the system.
Note that convolving two signals is equivalent to multiplying the Fourier Transform of the two
signals.

Mathematic Formula:
The linear convolution of two continuous time signals x(t) and h(t) is defined by

For discrete time signals x(n) and h(n), is defined by

Where x(n) is the input signal and h(n) is the impulse response of the system.
In linear convolution length of output sequence is,
length(y(n)) = length(x(n)) + length(h(n)) – 1

Graphical Interpretation:
 Reflection of h(k) resulting in h(-k)
 Shifting of h(-k) resulting in h(n-k)
 Element wise multiplication of the sequences x(k) and h(n-k)
 Summation of the product sequence x(k) h(n-k) resulting in the convolution value for y(n)

Example:
x(n) = {1, 2, 3, 1}
h(n) = {1, 1, 1}
length(y(n)) = length(x(n)) + length(h(n)) – 1

=4+3–1=6

Dept. of ECE, JSSATE, Bengaluru-60 Page 12


Digital Signal Processing Lab (15ECL57) V Semester

x(k) h(k)
3
2
1 1 1 1 1

-4 -3 -2 -1 0 1 2 3 4 5 6 7 0 1 2


n=0; h(-k ) y(0) = ∑ x(k) h(-k) = 1
1 k=-∞

-4 -3 -2 -1 0 1 2 3 4 5 6 7


n=1; h(1-k) y(1) = ∑ x(k) h(1-k) = 1+2=3
1 k=- ∞

-4 -3 -2 -1 0 1 2 3 4 5 6 7


n=2; h(2-k) y(2) =∑ x(k) h(2-k) = 1+2+3=6
1 k=-∞

-4 -3 -2 -1 0 1 2 3 4 5 6 7


n=3; h(3-k) y(3) =∑ x(k) h(3-k) = 2+3+1=6
1 k=-∞

-4 -3 -2 -1 0 1 2 3 4 5 6 7


n=4; h(4-k) y(4) = ∑ x(k) h(4-k) = 3+1=4
1 k=-∞

-4 -3 -2 -1 0 1 2 3 4 5 6 7


n=5; h(5-k) y(5) = ∑ x(k) h(5-k) = 1
1 k=-∞

-4 -3 -2 -1 0 1 2 3 4 5 6 7

6 6

4
3
y(n) = {1, 3, 6, 6, 4, 1}

1 1
-4 -3 -2 -1 0 1 2 3 4 5 6 7

Dept. of ECE, JSSATE, Bengaluru-60 Page 13


Digital Signal Processing Lab (15ECL57) V Semester

Program: Linear Convolution of given sequence

clear;
clc;
x=input(„ Enter the sequence x „ );
h=input((„ Enter the sequence h „);
l1=length(x);
l2=length(h);
l=l1+l2-1;
for n=1:l
z=0;
for k=1:l1
if(((n-k+1)>0) & ((n-k+1)<=l2))
z=z+(x(k)*h(n-k+1));
end;
res(n)=z;
end;
end;

figure
subplot(4,1,1)
stem(x)
title(„x(n)‟)
xlabel(„Time‟);
ylabel(„Amplitude‟);

subplot(4,1,2)
stem(h)
title(„h(n)‟)
xlabel(„Time‟);
ylabel(„Amplitude‟);
subplot(4,1,3)
stem(res)
title(„z(n)‟)
xlabel(„Time‟);
ylabel(„Amplitude‟);
z1=conv(x,h)
subplot(4,1,4)
stem(z1)
title(„z1(n)‟)
xlabel(„Time‟);
ylabel(„Amplitude‟);

Output:
Enter the first sequence
x[1 2 3 4]
Enter the second sequence
h[3 4 5 6]

Dept. of ECE, JSSATE, Bengaluru-60 Page 14


Digital Signal Processing Lab (15ECL57) V Semester

Output without Built in z


3 10 22 40 43 38 24
Output with Built in z1
3 10 22 40 43 38 24

Dept. of ECE, JSSATE, Bengaluru-60 Page 15


Digital Signal Processing Lab (15ECL57) V Semester

Properties of Linear Convolution

Property No. 1: Commutative property x+h=h+x


close all; clear all;
%commutative property x+h=h+x
x=input('enter the sequence x(n)');
h=input('enter the sequence h(n) ');

z1=conv(x,h);
z2=conv(h,x);
if(z1==z2)
disp(‟Commutative property satisfied‟);
else
disp(„‟commutative property satisfied‟);
end
display(z1);
display(z2);

Output:
„commutative property satisfied‟

Property No. 2: Associative property (x1*x2) *x3 =x1*(x2*x3)

%associative property (x1*x2) *x3 =x1*(x2*x3)


close all; clear all;

x1=input('x1(n)'); %enter the sequence


x2=input('x2(n)');
x3=input('x3(n)');

h=conv(x1,x2);
i=conv(h,x3);
j=conv(x2,x3);
k=conv(x1,j);
if(i==k)
disp(‟associative property satisfied‟);
else
disp(‟associative property satisfied‟);
end

display(i);
display(k);

Output:
„associative property satisfied‟

x1(n) =[1 1 1]
Dept. of ECE, JSSATE, Bengaluru-60 Page 16
Digital Signal Processing Lab (15ECL57) V Semester

x2(n)= [2 2 2 2]
x3(n)=[ 3 3 3 3]
i = 6 18 36 54 60 54 36 18 6
k =6 18 36 54 60 54 36 18 6

Property No. 3: Distributive property x*(h1+h2)=(x*h1)+(x*h2)

%distributive property x*(h1+h2)=(x*h1)+(x*h2)


close all; clear all;

x=input('x(n)');
h1=input('h1(n)');
h2=input('h2(n)');

h=h1+h2;
i=conv(x,h);
j=conv(x,h1);
k=conv(x,h2);
l=j+k;
if(i==l)
disp(‟ distributive property satisfied‟);
else
disp(‟ distributive property satisfied‟);
end

display(i);
display(l);

Output:
„ Distributive property satisfied‟

x(n)[1 1 1 1]
h1(n)[2 2 2 2]
h2(n)[3 3 3 3]
h=5 5 5 5
i = 5 10 15 20 15 10 5
l = 5 10 15 20 15 10 5

Applications:
1. Convolution amplifies or attenuates each frequency component of the input independently of
the other components.
2. In statistics, a weighted moving average is a convolution.
3. In probability theory, the probability distribution of the sum of two independent random
variables is the convolution of their individual distributions.
4. In digital image processing, convolutional filtering plays an important role in many important
algorithms in edge detection.
5. In radiotherapy treatment planning systems, most apart of all modern codes of calculation
applies a convolution-superposition algorithm
Dept. of ECE, JSSATE, Bengaluru-60 Page 17
Digital Signal Processing Lab (15ECL57) V Semester

2. b. Circular Convolution
Let x1(n) and x2(n) are finite duration sequences both of length N with DFT‟s X1(k) and X2(k).
Convolution of two given sequences x1(n) and x2(n) is given by the equation,
x3(n) = IDFT[X3(k)]
X3(k) = X1(k) X2(k)
N-1
x3(n) = ∑ x1(m) x2((n-m))N
m=0

Example:
Let‟s take x1(n) = {1, 1, 2, 1} and
x2(n) = {1, 2, 3, 4}
Arrange x1(n) and x2(n) in circular fashion as shown below.
x1(m) x2(m)

1 2
X1 (1) X2 (1)

X1 (2) X1 (0) X2 (2) X2 (0)


2 1 3 1

X1 (3) X2 (3)
1 4

To get x2(-m), rotate x2(m) by 4 samples in clockwise direction. x2(-m)

4
X2 (3)

X2(2) X2 (0)
3 1

X2(1)
2

Dept. of ECE, JSSATE, Bengaluru-60 Page 18


Digital Signal Processing Lab (15ECL57) V Semester

x3(0) = x1(m) x2(-m)

= x1(0) x2(0) + x1(1) x2(3) + x1(2) x2(2) + x1(3) x2(1)

= 1 + 4 + 6 +2

x3(0) = 13

Keep x1(m) constant and rotate x2(-m) once to compute further values.

To get x3(1) rotate x2(-m) by one sample in anti-clockwise direction

x2(1-m)

1
X2 (0)

X2(3) X2 (1)
4 2

1
X2(2)
3
x3(1) = x1(m) x2(1-m)

= x1(0) x2(1) + x1(1) x2(0) + x1(2) x2(3) + x1(3) x2(2)

=2+1+8+3

x3(1) = 14

To get x3(2) rotate x2(1-m) by one sample in anti-clockwise direction x2(2-m)

2
X2 (1)

1 3
X2(2)
X2(0)

X2(3)
4

Dept. of ECE, JSSATE, Bengaluru-60 Page 19


Digital Signal Processing Lab (15ECL57) V Semester

x3(2) = x1(m) x2(2-m)

= x1(0) x2(2) + x1(1) x2(1) + x1(2) x2(0) + x1(3) x2(3)

= 3 + 2 + 2+ 4

x3(2) = 11

To get x3(3) rotate x2(2-m) by one sample in anti-clockwise direction

x2(3-m)

3
X2 (2)

2 4
X2(1) X2(3)

X2(0)
1
x3(3) = x1(m) x2(3-m)

= x1(0) x2(3) + x1(1) x2(2) + x1(2) x2(1) + x1(3) x2(0)

=4+3+4+1

x3(3) = 12

The convoluted signal is,

x3(n) = {13, 14, 11, 12}

Program:

% Circular Convolution

clear;
clc;
close all;
x=input('Enter the sequence x(n)');
h=input('Enter the sequence h(n)');
g=input('Enter the sequence g(n)');

N1=length(x);
N2=length(h);
N3=length(g);
N=max(N1,max(N2,N3));

Dept. of ECE, JSSATE, Bengaluru-60 Page 20


Digital Signal Processing Lab (15ECL57) V Semester

x =[x zeros(1,N-N1)];
h =[h zeros(1,N-N2)];
g =[g zeros(1,N-N2)];

% Without builtin function

for i=0:N-1
m(i+1) = mod(-i,N);
end
h1=h(m+1);
for i=1:N
y(i) =x*h1';
h1=[h1(N) h1(1:N-1)];
end
disp('y');
disp(y)

% With builtin function

% type the user defined function circonv.m in a new m file


function[g] = circonv(x,h)
g=[];
N1=length(x);
N2=length(h);
N=max(N1,N2);

for i=0:N-1
x1(:,i+1)=circshift(x',i);
end
g=x1*h';

y1=circonv(x,h)
figure;
n=0:1:N-1;
subplot(3,1,1);
stem(n,x);
xlabel('time');
ylabel('amplitude');
title('Input Sequence x(n)');
subplot(3,1,2);
stem(n,h);
xlabel('time');
ylabel('amplitude');
title('Input Sequence h(n)');
subplot(3,1,3);
stem(n,y);
xlabel('time');
ylabel('amplitude');
title('output sequence y(n)');
Dept. of ECE, JSSATE, Bengaluru-60 Page 21
Digital Signal Processing Lab (15ECL57) V Semester

Output:

Enter the sequence x(n)[1 2 3 4]


Enter the sequence h(n)[3 4 5 6]
Enter the sequence g(n)[1 2 1 1]
y
46 48 46 40

y1 =

46
48
46
40

Graph for Circular Convolution

Properties of Circular Convolution :

Property No. 1: Commutative property x+h=h+x


% commuative x,h=h,x
LHS_comm=circonv(x,h);
RHS_comm=circonv(h,x);
if (LHS_comm==RHS_comm)
disp ('comm property is satisfied');
else
disp ('comm property is not satisfied');
end
figure;
subplot(3,2,1)
stem(LHS_comm)
Dept. of ECE, JSSATE, Bengaluru-60 Page 22
Digital Signal Processing Lab (15ECL57) V Semester

title('LHS');
xlabel('time');
ylabel('amplitude');

subplot(3,2,2)
stem(RHS_comm)
title('RHS');
xlabel('time');
ylabel('amplitude');

Output:
comm property is satisfied

Property No. 2: Associative property (x*h) *g =x*(h*g)


temp=circonv(x,h)
LHS_asso=circonv(temp',g)
temp=circonv(h,g)
RHS_asso=circonv(x,temp');
disp('LHS_asso');
disp(LHS_asso);
disp('RHS_asso');
disp(RHS_asso);
if (LHS_asso==RHS_asso)
disp('associative property is satisfied');
else
disp('associative property is not satisfied');
end

subplot(3,2,3)
stem(LHS_asso)
title('LHS');
xlabel('time');
ylabel('amplitude');

subplot(3,2,4)
stem(RHS_asso)
title('RHS');
xlabel('time');
ylabel('amplitude');

Output:
temp =

46
48
46
40

LHS_asso =
Dept. of ECE, JSSATE, Bengaluru-60 Page 23
Digital Signal Processing Lab (15ECL57) V Semester

220
226
228
226

temp =

24
21
22
23

LHS_asso
220
226
228
226

RHS_asso
220
226
228
226

associative property is satisfied

Property No. 3: Distributive property x*(h+g)=(x*h)+(x*g)


LHS_dist=circonv(x,(h+g));
RHS_dist=(circonv(x,h)+circonv(x,g));
disp('LHS_dist');
disp(LHS_dist);
disp('RHS_dist');
disp(RHS_dist);
if (LHS_dist==RHS_dist)
disp('distributive property is satisfied');
else
disp('distributive property is not satisfied');
end
subplot(3,2,5)
stem(LHS_comm)
title('LHS');
xlabel('time');
ylabel('amplitude');

subplot(3,2,6)
stem(RHS_asso)
title('RHS');
xlabel('time');
ylabel('amplitude');
Dept. of ECE, JSSATE, Bengaluru-60 Page 24
Digital Signal Processing Lab (15ECL57) V Semester

Output:

LHS_dist
60
59
58
53

RHS_dist
60
59
58
53
distributive property is satisfied

Circular Convolution Properties Graph:

Commutative property

Associative property

Distributive property

Application:

1. Linear filtering – Overlap save and add method.

Dept. of ECE, JSSATE, Bengaluru-60 Page 25


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 3: Write a MATLAB code to compute Auto and Cross Correlation of


two given sequences and verification of their properties.

3. a. Auto Correlation
Correlation: Correlation determines the degree of similarity between two signals. If the signals
are identical, then the correlation coefficient is 1; if they are totally different, the correlation
coefficient is 0, and if they are identical except that the phase is shifted by exactly 180 0(i.e.
mirrored), then the correlation coefficient is -1.

Autocorrelation: When the same signal is compared to phase shifted copies of itself, the
procedure is known as autocorrelation.
The autocorrelation of a random signal describes the general dependence of the values of the
samples at one time on the values of the samples at another time. Consider a random process
x(t) (i.e. continuous time), its autocorrelation function is,

Where T is the period of observation.


Rxx (τ) is always real valued and an even function with a maximum value at τ = 0.

For sampled signal, the autocorrelation function is defined as,

Biased autocorrelation
….. Eqn.1

Unbiased autocorrelation
For m = 1 + 2 + …. + M+1
Where M is the number of lags.
Example: Auto Correlation of a sine wave.
Plot the autocorrelation of a sine wave with frequency of 1 Hz, sampling frequency of 200 Hz.
Note that we used the function xcorr to estimate the autocorrelation sequence, it has
double the number of samples as the signal x(n). An important point to remember when
using the function xcorr is that the origin is in the middle of the figure (here it is at lag =
1024). xcorr is a built in function in MATLAB library.

Dept. of ECE, JSSATE, Bengaluru-60 Page 26


Digital Signal Processing Lab (15ECL57) V Semester

Program:

clc;
clear;
x=input(„Enter the sequence\n‟);
l1=length(x);
y=fliplr(x);
l2=length(y);
l=l1+l2-1;

for n=1:l
z=0;
for k=1:l1
if((n-k+1)>0 & (n-k+1)<=l2)
z=z+(x(k)*y(n-k+1));
end;
Rxx(n)=z;
end;
end;

figure;
subplot(3,1,1);
stem(x);
xlabel(„Time‟);
ylabel(„Amplitude‟);
title(„Input sequence x(n)‟);

subplot(3,1,2);
stem(Rxx);
xlabel(„Time‟);
ylabel(„Amplitude‟);
title(„Autocorrelation without using builtin function‟);
disp(„Autocorrelation without using builtin‟);
disp(Rxx);

% Autocorrelation using built in function

Rxx1=xcorr(x);
subplot(3,1,3);
stem(Rxx1);
xlabel(„Time‟);
ylabel(„Amplitude‟);
title(„Autocorrelation using builtin function‟);
disp(„Autocorrelation using builtin‟);
disp(Rxx1);

%Property 1 - Autocorrelation is Symmetric

Rxx_flip=fliplr(Rxx);

Dept. of ECE, JSSATE, Bengaluru-60 Page 27


Digital Signal Processing Lab (15ECL57) V Semester

if Rxx==Rxx_flip
disp(„Autocorrelation is symmetric‟);
figure;
subplot(3,2,1);
stem(Rxx);
xlabel(„Time‟);
ylabel(„Amplitude‟);
title(„Rxx‟);
subplot(3,2,2);
stem(Rxx_flip);
xlabel(„Time‟);
ylabel(„Amplitude‟);
title(„ = Flipped Rxx‟);
else
disp(„Autocorrelation is not symmetric‟);
end

%Property 2 - Autocorrelation is an Even Function

center_index=ceil(length(Rxx)/2);
Rxx_right=Rxx(center_index:1:length(Rxx));
Rxx_left=Rxx(center_index:-1:1);

if (Rxx_right==Rxx_left)
disp(„Property satisfied, Autocorrelation is even‟);
subplot(3,2,3);
stem(Rxx_left);
xlabel(„Time‟);
ylabel(„Amplitude‟);
title(„Rxx(m)‟);
subplot(3,2,4);
stem(Rxx_right);
xlabel(„Time‟);
ylabel(„Amplitude‟);
title(„ = Rxx(-m)‟);
else
disp(„Property not satisfied‟);
end;

%Property 3 - Energy of signal is denoted by the value at t=0


energy=sum(x.^2);
center_index=ceil(length(Rxx)/2);
Rxx0=Rxx(center_index);
if(Rxx0==energy)
disp(„autocorrelation at t=0 gives energy,hence proved‟);
subplot(3,2,[5,6]);
stem(Rxx0);
xlabel(„Time‟);
ylabel(„Amplitude‟);

Dept. of ECE, JSSATE, Bengaluru-60 Page 28


Digital Signal Processing Lab (15ECL57) V Semester

title(„ Energy is at t=0‟);


else
disp(„autocorrelation at t=0 does not gives energy, not proved‟);
end;

Output:

Enter the sequence


[1 2 3 4]

Autocorrelation without using builtin


4 11 20 30 20 11 4

Autocorrelation using builtin


4.0000 11.0000 20.0000 30.0000 20.0000 11.0000 4.0000

Autocorrelation is symmetric
Property satisfied, Autocorrelation is even
autocorrelation at t=0 gives energy, hence proved

Dept. of ECE, JSSATE, Bengaluru-60 Page 29


Digital Signal Processing Lab (15ECL57) V Semester

Properties of Auto Correlation:

Applications :

1. The measurement of optical spectra and the measurement of very-short-duration light pulses
produced by lasers, both using optical auto correlators.
2. In signal processing, autocorrelation can give information about repeating events like musical
beats (for example, to determine tempo) or pulsar frequencies, though it cannot tell the position
in time of the beat. It can also be used to estimate the pitch of a musical tone.
3. In music recording, autocorrelation is used as a pitch detection algorithm prior to vocal
processing, as a distortion effect or to eliminate undesired mistakes and inaccuracies.
4. In optics, normalized autocorrelations and cross-correlations give the degree of coherence of an
electromagnetic field.

Dept. of ECE, JSSATE, Bengaluru-60 Page 30


Digital Signal Processing Lab (15ECL57) V Semester

3. b. Cross Correlation

Correlation: Correlation determines the degree of similarity between two signals. If the signals
are identical, then the correlation coefficient is 1; if they are totally different, the correlation
coefficient is 0, and if they are identical except that the phase is shifted by exactly 1800(i.e.
mirrored), then the correlation coefficient is -1.
Cross-correlation: When two independent signals are compared, the procedure is known as
cross-correlation.
The cross correlation function measures the dependence of the value of one signal on another signal. For
two WSS (Wide Sense Stationary) processes x(t) and y(t) it is described by,

Or

Where T is the observation time.


For sampled signals, cross-correlation is defined as,

For m = 1 + 2 + ….. + N+1


Where N is the record length (i.e. number of samples).

Example:
Plot the cross correlation for the following signal,
x(n) = sin(2πf1t) with f1 = 1 Hz
y(n) = x(n) + w(n)
Where w(n) is a zeroes mean, unit variance of Gaussian random process.

Dept. of ECE, JSSATE, Bengaluru-60 Page 31


Digital Signal Processing Lab (15ECL57) V Semester

Program:

clear;
clc;
x=input(„ Enter the sequence of x „);
y=input(„ Enter the sequence of y „);
L1=length(x);
L2=length(y);
L=L1+L2-1;

y1=fliplr(y);
for n=1:L
z=0;
for k=1:L1
if((n-k+1)>0 & (n-k+1)<=L2)
z=z+(x(k)*y1(n-k+1));
end;
end;
Rxy(n)=z;
end;

subplot(4,1,1);
stem(x);
subplot(4,1,2);
stem(y);
subplot(4,1,3);
stem(Rxy);
title(„Cross correlation without using builtin function‟);
disp(„Cross correlation without using builtin function‟);
disp(Rxy);

% Cross Correlation using builtin function

Rxy1=xcorr(x,y);
subplot(4,1,4);
stem(Rxy1);
title(„Cross correlation using builtin function‟);
disp(„Cross correlation using builtin function‟);
disp(Rxy1);

% Properties
% Properties 1 - Rxy(n) = Ryx(-n)

Rxy_flip= fliplr(Rxy);
figure;
subplot(3,2,1);
stem(Rxy);
title( „Rxy(n)‟);
subplot(3,2,2);

Dept. of ECE, JSSATE, Bengaluru-60 Page 32


Digital Signal Processing Lab (15ECL57) V Semester

stem(Rxy_flip);
title( „ = Rxy(-n)‟);

% Properties 2 - |Rxy(n)| <= 1/2[Rxx(0)+Ryy(0)]

Rxx = xcorr(x,x);
Ryy = xcorr(y,y);
Rxyabs = abs(Rxy)
centre_index = ceil(length(Rxx)/2);
Rxx0 = Rxx(centre_index);
centre_index = ceil(length(Ryy)/2);
Ryy0 = Ryy(centre_index);
Rxx0plusRyy0by2 = (Rxx0 + Ryy0)/2
if Rxyabs <= Rxx0plusRyy0by2
disp(„Property 2 is satisfied‟);
subplot(3,2,3);
stem(Rxyabs);
title(„|Rxy(n)|‟);
subplot(3,2,4);
stem(Rxx0plusRyy0by2);
title(„<= 1/2(Rxx0 + Ryy0)‟);
else
disp(„Property 2 is not satisfied‟);
end;

% Properties 2 - |Rxy(n)|^2 <= [Rxx(0)*Ryy(0)]

Rxyabssq = Rxyabs.^2;
prodRxx0andRyy0 = Rxx0 * Ryy0
if Rxyabssq <= prodRxx0andRyy0
disp(„Property 3 is satisfied‟);
subplot(3,2,5);
stem(Rxyabssq);
title(„|Rxy(n)|^2‟);
subplot(3,2,6);
stem(prodRxx0andRyy0);
title(„<= (Rxx0 * Ryy0)‟);
else
%disp(„Property 3 is not satisfied‟);
end;

Dept. of ECE, JSSATE, Bengaluru-60 Page 33


Digital Signal Processing Lab (15ECL57) V Semester

Output:

Properties of Cross Correlation:

Applications:
1. Study of signals comparatively and understanding its behavior.
2. The cross-correlation function is used extensively in pattern recognition and signal detection.

Dept. of ECE, JSSATE, Bengaluru-60 Page 34


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 4: Write a MATLAB code to solve a given Difference Equation.

A General Nth order Difference equations looks like,

y[n] + a1y[n-1] + a2y[n-2] + …+ aNy[n-N) =


b0x[n] + b1x[n-1] + …. + bMx[n-M]
Here y[n] is “Most advanced” output sample and y[n-m] is “Least advanced” output sample.
The difference between these two index values is the order of the difference equation.
Here we have: n-(n-N) = N
We can rewrite the above equation as,

y[n] + ∑ai y[n-i] = ∑bi x[n-i]

y[n] becomes,

y[n] = -∑ai y[n-i] + ∑bi x[n-i]

Example:

y[n+2] – 1.5y[n+1] + y[n] = 2x[n]

In general we start with the “Most advanced” output sample. Here it is y[n+2].

So, here we need to subtract 2 from each sample argument. We get

y[n] – 1.5y[n-1] + y[n-2] = 2x[n-2]

 y[n] = 1.5y[n-1] - y[n-2] + 2x[n-2]

Lets assume our input x[n] = u[n] = 0 x<0


1 x≥0

In our example we have taken x[n] = u[n] = 0 x<0


1 0≤x<10

We need N past values to solve Nth order difference equation.


y[-2] = 1
y[-1] = 2

Compute y[n] for various values of n


y[0] = 1.5y[-1] - y[-2] + 2x[-2]
= 1.5*2 – 1 + 2*0
y[0] = 2

y[1] = 1.5y[0] - y[-1] + 2x[-1]


= 1.5*2 - 2 + 2*0
y[1] = 1
y[2] = 1.5y[1] - y[0] + 2x[0]
= 1.5*1 – 2 + 2*1
y[2] = 1.5
And so on…
Dept. of ECE, JSSATE, Bengaluru-60 Page 35
Digital Signal Processing Lab (15ECL57) V Semester

Program:
clc;
clear;
a= input(„ Enter the coefficients of a „);
b= input(„ Enter the coefficients of b „);
x= input(„ Enter the input x „);
h= DifferenceEquation(b,a,x)
subplot(2,1,1);
stem(n,h);
title(„ Output without builtin function „);
% With builtin function
h1= filter(b,a,x)
subplot(2,1,2);
stem(n,h1);
title(„ Output with builtin function „);
% store the function as DifferenceEquation.m in different file
function[g]=DifferenceEquation(b,a,x);
g=[];
for n=0:length(x)-1
sum1=0;
sum=0;
for k1=1:length(a)-1
if((n-k1+1)>0)
sum1=sum1+(a(k1+1)*g(n-k1+1));
end;
end;
for k=0:length(b)-1
if((n-k+1)>0)
sum=sum+(b(k+1)*x(n-k+1));
end;
end;
g(n+1)=(sum-sum1)/a(1);
end;
Output:
Enter the coefficients of a [1 0.7 -0.45 -0.6]
Enter the coefficients of b [0.8 -0.44 0.36 0.02]
Enter the input x [1 5 -2 6]
Output without builtin function
h = 0.8000 3.0000 -5.1800 12.9560
Output with builtin function
h1 = 0.8000 3.0000 -5.1800 12.9560
Applications:
1. Implementation of digital filters.(Fixed point)
2. Realization of Digital filters.

Dept. of ECE, JSSATE, Bengaluru-60 Page 36


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 5: Write a MATLAB code to computation of N point DFT of a given


sequence and plot the magnitude and phase spectrum (using DFT equation and
verify it by built-in routine).
Discrete Fourier Transform: The Discrete Fourier Transform is a powerful computation tool
which allows us to evaluate the Fourier Transform X(ejω) on a digital computer or specially
designed digital hardware. Since X(ejω) is continuous and periodic, the DFT is obtained by
sampling one period of the Fourier Transform at a finite number of frequency points. Apart
from determining the frequency content of a signal, DFT is used to perform linear filtering
operations in the frequency domain.

The sequence of N complex numbers x0,..., xN−1 is transformed into the sequence of N complex
numbers X0, ..., XN−1 by the DFT according to the formula:

N-1
X(k) = ∑x(n)e-j2πnk/N k = 0,1, …. N-1
n=0

Example:
Lets assume the input sequence x[n] = [1 1 0 0]

We have,
N-1
X(k) = ∑x(n)e-j2πnk/N k = 0,1, …. N-1
n=0

For k = 0,
3
X(0) = ∑x(n) = x(0) + x(1) + x(2) + x(3)
n=0
X(0) = 1+1+0+0 = 2

For k = 1,
3
X(1) = ∑x(n)e-jπn/2 = x(0) + x(1) e-jπ/2 + x(2) e-jπ + x(3) e-j3π/2
n=0
= 1 + cos(π/2) - jsin(π/2)
X(1) = 1 – j

For k = 2,
3
X(2) = ∑x(n)e-jπn = x(0) + x(1) e-jπ + x(2) e-j2π + x(3) e-j3π
n=0
X(2) = 1 + cos π – jsin π
X(2) = 1-1 = 0

For k = 3,
3
Dept. of ECE, JSSATE, Bengaluru-60 Page 37
Digital Signal Processing Lab (15ECL57) V Semester

X(3) = ∑x(n)e-j3nπ/2 = x(0) + x(1) e-j3π/2 + x(2) e-j3π + x(3) e-j9π/2


n=0
= 1 + cos(3π/2) - jsin(3π/2)
X(3) = 1 + j

The DFT of the given sequence is,


X(k) = { 2, 1-j, 0, 1+j }

Program:
clear;
clc;
x=input(„enter the sequence‟);
n=length(x);
y=fft(x,n);
t=0:1:n-1;
subplot(3,1,1);
stem(t,x);
title(„DFT output‟);
k=0:1:n-1;
subplot(3,1,2);
stem(t,abs(y));
subplot(3,1,3);
stem(k,angle(y));

%without built in %

clc;
clear;
x=input(„enter the sequence x‟);
N=length(x);
for n=1:N;
for k=1:N;
W(n,k)=exp((-j*2*pi*(k-1)*(n-1)/N));
end;
end;
y=W*x;
subplot(3,1,1)
stem(x,abs(y))
subplot(3,1,2)
stem(x,angle(y))
subplot(3,1,3)
stem(x,(y))

Applications:
1. Spectral analysis of the signal.
2. Speech processing.
3. Image processing.

Dept. of ECE, JSSATE, Bengaluru-60 Page 38


Digital Signal Processing Lab (15ECL57) V Semester

Experiments6. a.: Verification of DFT properties (like Linearity and Parsevals


theorem, etc.)

Linearity:
Let x0 , x1 ,......x N 1  and y 0 , y1 ,......y N 1  be two sets of discrete samples with corresponding

DFT‟s given by X (m) and Y (m) . Then DFT of sample set

x0  y0 , x1  y1 ,..........., x N 1  y N 1 is given by X (m)  Y (m)

N 1  j 2 nm N 1  j 2 nm

Proof: X ( m)   x n e N
; Y ( m)   y n e N

n 0 n 0

N 1  j 2 mn
X ( m)  Y ( m)   ( x n  y n ) e N

n 0

Program:

close all;
clear all;
N=input(„Howmany point DFT do you want?);
x1=input(„Enter the first sequence=‟);
x2=input(„Enter the first sequence=‟);
a=input(„Enter the first constant=‟);
b=input(„Enter the first constant=‟);
n1=length(x1);
n2=length(x2);
c=zeros(N);
x1=[x1zeros(1,N-n1)];%make bothx1 and x2
x2=[x2zeros(1,N-n2)];%of same dimension
x3=a*x1
x4=b*x2
x5=x3+x4%a*x1+b*x2
for k=1:N
for n=1:N
w=exp((-2*pi*i*(k-1)*(n-1))/N);
%prev.step=>evaluating w-matrix
x(n)=w;
end
c(k,:)=x; %every row of w-matrix is inserted &
end %finally c becomes the w matrix
% for n-point DFT
r1=c*x1‟; %x1(k)
r2=c*x1‟; %x2(k)
R3=a*r1+b*r2 %a*x1(k)+b*x2(k)

Dept. of ECE, JSSATE, Bengaluru-60 Page 39


Digital Signal Processing Lab (15ECL57) V Semester

r1=c*x1‟
b*r2 %a*x1(k)+b*x2(k)
R4=c*5‟ %DFT of a*x1(n)+b*x2(n)
%plotting magnitude and angle
subplot(211)
stem(abs(R4));
title(„DFT of{a*x1(n)+b*x2(n)}‟);
subplot(212)
stem(angle(R3));
title(„DFT of{a*x1(k)+b*x2(k)}‟);

Parseval Theorem:
Parseval's theorem states that the energy amounts found in the time domain must be equal to
the energy amounts found in the frequency domain:

Program:

close all;
clear all;
x=input(„Enter input sample x:‟);
y=input(„Enter second sample y:‟);
N1=length (x);N2=length(y);
N=max(N1,N2);
x=zeros(1,N);
y=zeros(1,N);
z=zeros(1,N);
if(N1>N2)
for n=N2+1:N1
y(n)=0;
end;
elseif(N2>N1)
for n=N1+1:N2
y(n)=0;
end;
end;
y1=conj (y);
disp:(„L.H.S‟);
z=0;
for n=1:N

z=z+x(n)*y1(n);
end;
disp (z);

Dept. of ECE, JSSATE, Bengaluru-60 Page 40


Digital Signal Processing Lab (15ECL57) V Semester

for k=1:N
for n=1:N
X(k)=X(k)+(x(n)*exp(-1j*2*pi*(n-1)*(k-1)/N));
Y(k)= Y(k)+(y(n)*exp(-1j*2*pi*(n-1)*(k-1)/N));
end;
end;

disp(„X(k)‟);
for k=1:N
disp(X(k));
end;
disp(„Y(k)‟);
for k=1:N
disp (Y(k));
end;

Y2=conj (Y);
disp(„[Y(k)]*‟);
for k=1:N
disp(Y2(k));
end:
z1=0;
disp(„R.H.S.‟);
for k=1:N
z1=z1+(X(k)*Y2(k))/N;
end;
disp(z1);
case 3
%COMPLEX CONJUGATE
x=input(„enter sample signal x:‟);
N=length (x);
X2=zeros(1,N);
X1= zeros(1,N);
Y= zeros(1,N);
y=conj(x);
for k=1:N
for n=1:N

Applications:

1. In discrete system realization.


2. In Energy calculation.

Dept. of ECE, JSSATE, Bengaluru-60 Page 41


Digital Signal Processing Lab (15ECL57) V Semester

Experiments 6. b.: DFT Computation of Square Pulse and Sinc Function etc

Program: DFT of a Square Pulse

% Square Wave

f=10; %frequency of sine wave in Hz


overSampRate=30; %oversampling rate
fs=overSampRate*f; %sampling frequency
duty_cycle=50; % Square wave with 50% Duty cycle (default)
nCyl = 5; %to generate five cycles of sine wave

t=0:1/fs:nCyl*1/f; %time base

x=square(2*pi*f*t,duty_cycle); %generating the square wave


subplot(2,1,1)
plot(t,x,'k');
title(['Square Wave f=', num2str(f), 'Hz']);
xlabel('Time(s)');
ylabel('Amplitude');

NFFT =1024;
X = fft(x,NFFT);
L=length(X);
X = X(1:NFFT/2+1);%Throw the samples after NFFT/2 for single sided plot
Pxx=X.*conj(X)/(NFFT*L);
f = fs*(0:NFFT/2)/NFFT; %Frequency Vector
subplot(2,1,2)
plot(f,10*log10(Pxx));
title('Single Sided Power Spectral Density');
xlabel('Frequency (Hz)')
ylabel('Power Spectral Density- P_{xx} dB/Hz');
ylim([-45 -5])

Dept. of ECE, JSSATE, Bengaluru-60 Page 42


Digital Signal Processing Lab (15ECL57) V Semester

Program: DFT of a Sinc Function

% DFT of a Sinc function

Fs=42;
Ts=1/Fs;
t=-1:Ts:40*Ts-Ts;
f=2;
y=sinc(pi*t*f);
subplot(2,1,1)
plot(t,y);
xlabel('x');
ylabel(' magnitude');
N=512;
fy=(fft(y,N));
subplot(2,1,2)
fr=(0:N-1)*Fs/N;
fy=fy(1:floor(end/2));
fr=fr(1:floor(end/2));
plot(fr,fftshift(abs(fy)));
xlabel(' frequency x^{-1}');
ylabel(' magnitude');

Dept. of ECE, JSSATE, Bengaluru-60 Page 43


Digital Signal Processing Lab (15ECL57) V Semester

Program: DFT of a Sine Function

% Plot of Sine Wave


f=10; %frequency of sine wave
overSampRate=30; %oversampling rate
fs=overSampRate*f; %sampling frequency
phase = 1/3*pi; %desired phase shift in radians
nCyl = 5; %to generate five cycles of sine wave
t=0:1/fs:nCyl*1/f; %time base
x=sin(2*pi*f*t+phase); %replace with cos if a cosine wave is desired
subplot(2,1,1)
plot(t,x);
title(['Sine Wave f=', num2str(f), 'Hz']);
xlabel('Time(s)');
ylabel('Amplitude');

% DFT OF Sine Wave

NFFT=1024; %NFFT-point DFT


X=fft(x,NFFT); %compute DFT using FFT
nVals=0:NFFT-1; %DFT Sample points
subplot(2,1,2)
plot(nVals,abs(X));

Dept. of ECE, JSSATE, Bengaluru-60 Page 44


Digital Signal Processing Lab (15ECL57) V Semester

title('Double Sided FFT - without FFTShift');


xlabel('Sample points (N-point DFT)')
ylabel('DFT Values');

Dept. of ECE, JSSATE, Bengaluru-60 Page 45


Digital Signal Processing Lab (15ECL57) V Semester

Experiments 7: Design and implementation of FIR filter to meet given


specifications (using different window techniques).

Finite Impulse Response (FIR) Filter:

The FIR filters are of non-recursive type, whereby the present output sample is
depending on the present input sample and previous input samples.
The transfer function of a FIR causal filter is given by,
N-1
H(z) = ∑ h(n)z-n
n=0

Where h(n) is the impulse response of the filter.

The Fourier transform of h(n) is


N-1
H(ejw) = ∑h(n)e-jwn
n=0
In the design of FIR filters most commonly used approach is using windows.
The desired frequency response Hd(ejw) of a filter is periodic in frequency and can be expanded
in Fourier series. The resultant series is given by,
π
hd(n) = (1/2π) ∫ H(ejw)ejwn dw

And known as Fourier coefficients having infinite length. One possible way of obtaining FIR
filter is to truncate the infinite Fourier series at n = ± [(N-1)/2]
Where N is the length of the desired sequence.
The Fourier coefficients of the filter are modified by multiplying the infinite impulse response
with a finite weighing sequence w(n) called a window.

Where w(n) = w(-n) ≠ 0 for |n| ≤ [(N-1)/2]


=0 for |n| > [(N-1)/2]
After multiplying w(n) with hd(n), we get a finite duration sequence h(n) that satisfies the
desired magnitude response,
h(n) = hd(n) w(n) for |n| ≤ [(N-1)/2]
=0 for |n| > [(N-1)/2]
Dept. of ECE, JSSATE, Bengaluru-60 Page 46
Digital Signal Processing Lab (15ECL57) V Semester

The frequency response H(ejw) of the filter can be obtained by convolution of Hd(ejw) and
W(ejw) is given by,
π
H(e ) = (1/2π) ∫ Hd(ejθ) W(ej(w-θ) dθ
jw


H(e ) = Hd(e ) * W(ejw)
jw jw

Example:
Here we design a lowpass filter using hamming window.
Hamming window function is given by,

wH(n) = 0.54 + 0.46 cos ((2πn)/(N-1)) for –(N-1)/2 ≤ n ≤ (N-1)/2


=0 otherwise
The frequency response of Hamming window is,

WH(ejw ) = 0.54[(sin(wN/2))/(sin(w/2))]
+ 0.23[sin (wN/2 – πN/N – 1)/sin (w/2 – π/N -1)]
+ 0.23[sin (wN/2 + πN/N – 1)/sin (w/2 + π/N – 1)]

Program:

clc;
wp = input('Pass band edge freq:');
ws = input('Stop band edge freq:');
tw = ws-wp;
N = ceil(6.6*pi/tw)+1;
wn = (hamming(N));
B = fir1(N-1,wp,wn);
disp('Impulse response coeff=');
disp(B);
[H,w] = freqz(B,1,256);
Mag = 20*log10(abs(H));
plot(w/pi*pi, Mag);
xlabel(„Frequency in radians in terms of pi');
ylabel('Gain in db');

Dept. of ECE, JSSATE, Bengaluru-60 Page 47


Digital Signal Processing Lab (15ECL57) V Semester

Output:

Pass band edge freq: 0.05*pi


Stop band edge freq: 0.4*pi
Impulse response coeff=
Columns 1 through 7

-0.0027 -0.0035 -0.0041 -0.0010 0.0105 0.0333 0.0666

Columns 8 through 14

0.1046 0.1383 0.1580 0.1580 0.1383 0.1046 0.0666

Columns 15 through 20

0.0333 0.0105 -0.0010 -0.0041 -0.0035 -0.0027

-10

-20

-30

-40
Gain in db

-50

-60

-70

-80

-90

-100
0 0.5 1 1.5 2 2.5 3 3.5
Frequency in radians in terms of pi

Applications:
1. Linear phase applications.
2. In multirate systems.
3. In interpolation filter.

Note: Students can choose some of the applications for their presentation.

Dept. of ECE, JSSATE, Bengaluru-60 Page 48


Digital Signal Processing Lab (15ECL57) V Semester

Experiments 8: Design and implementation of IIR filter to meet given


specifications.

Infinite Impulse Response (IIR) Filter:

IIR filters are of recursive type, whereby the present output sample depends on the present
input, past input samples and output samples.
The impulse response h(n) for a realizable filter is,
h(n) = 0 for n≤0

And for stability, it must satisfy the condition,



∑ | h(n) | < ∞
n=0

Example:
Let‟s design an analog Butterworth lowpass filter.
Steps to design an analog Butterworth lowpass filter.
1. From the given specifications find the order of the filter N.
2. Round off it to the next higher integer.
3. Find the transfer function H(s) for Ωc = 1rad/sec for the value of N.
4. calculate the value of cutoff frequency Ωc
5. find the transfer function Ha(s) for the above value of Ωc by substituting
s→ (s/ Ωc) in H(s).

IIR filter Design using Bilinear Transformation and Impulse Invariance Method for Butterworth Filter

Program:

Program to design Low pass Butterworth filter using Bilinear Transformation


wp=input('Enter the passband edge =');
ws=input('Enter the stopband edge =');
pa=input('Enter the passband ripple =');
sa=input('Enter the stopband ripple =');
fs=input('Enter the sampling frequency =');
wp=wp*2*pi;
ws=ws*2*pi;
[n,wn]=buttord(wp,ws,pa,sa,'s')
[b,a]=butter(n,wn,'s')
printsys(b,a,'s')
[z,p,k]=tf2zp(b,a)
[zd,pd,kd]=bilinear(z,p,k,fs)
[num,den]=zp2tf(zd,pd,kd)
figure(1)
freqz(num,den,512,fs)
title('BUTTERWORTH FREQUENCY RESPONSE OF THE GIVEN FILTER')

Dept. of ECE, JSSATE, Bengaluru-60 Page 49


Digital Signal Processing Lab (15ECL57) V Semester

Output:
Enter the passband edge = 500
Enter the stopband edge = 750
Enter the passband ripple = 0.5
Enter the stopband ripple = 15
Enter the sampling frequency = 8000

n=7
wn = 3.6906e+003
b = 1.0e+024 *
Columns 1 through 7
0000000
ghgh
Column 8
9.3254
a = 1.0e+024 *
Columns 1 through 7
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0114
Column 8
9.3254
num/den =
9.325361e+024
--------------------------------------------------------------
s^7 + 16585.3338 s^6 + 137536649.0014 s^5 + 733489599957.645 s^4+ 2.707005e+015 s^3 +
6.913591e+018 s^2 + 1.135533e+022 s + 9.325361e+024

Dept. of ECE, JSSATE, Bengaluru-60 Page 50


Digital Signal Processing Lab (15ECL57) V Semester

Program:

Program to design Low pass Butterworth filter using Impulse Invariance Transformation

pb=input('Enter the passband edge =');


sb=input('Enter the stopband edge =');
pbr=input('Enter the passband ripple =');
sbr=input('Enter the stopband ripple =');
fs=input('Enter the sampling frequency =');
pbrad=pb*2*pi;
sbrad=sb*2*pi;
[n,wn]=buttord(pbrad,sbrad,pbr,sbr,'s')
[b,a]=butter(n,wn,'s')
[num,den]=impinvar(b,a,fs)
figure(1)
freqz(num,den,512,fs)
title('BUTTERWORTH FREQUENCY RESPONSE OF THE GIVEN FILTER')

Output:

Enter the passband edge =500


Enter the stopband edge =750
Enter the passband ripple =0.5
Enter the stopband ripple =30
Enter the sampling frequency =8000
n = 12
wn = 3.5339e+003
b = 1.0e+042 *
Columns 1 through 7
0000000
Columns 8 through 13
0 0 0 0 0 3.7941
a = 1.0e+042 *
Columns 1 through 7
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 8 through 13
0.0000 0.0000 0.0000 0.0000 0.0082 3.7941
num =
1.0e-005 *
Columns 1 through 7
0.0000 -0.0000 0.0002 0.0088 0.0954 0.3158 0.3840
Columns 8 through 13
0.1798 0.0309 0.0016 0.0000 -0.0000 0
den =
Columns 1 through 7
1.0000 -8.6530 34.6749 -85.0151 141.9295 -169.8641 149.3596
Columns 8 through 13
-97.1712 46.4033 -15.8567 3.6792 -0.5203 0.0339

Dept. of ECE, JSSATE, Bengaluru-60 Page 51


Digital Signal Processing Lab (15ECL57) V Semester

IIR filter Design using Bilinear Transformation and Impulse Invariance Method for Chebychev Filter

Program:

Program to design Low pass Chebychev filter using Bilinear Transformation


pb=input('Enter the passband edge =');
sb=input('Enter the stopband edge =');
pbr=input('Enter the passband ripple =');
sbr=input('Enter the stopband ripple =');
fs=input('Enter the sampling frequency =');
pbrad=pb*2*pi;
sbrad=sb*2*pi;
[n,wn]=cheb1ord(pbrad,sbrad,pbr,sbr,'s')
[b,a]=cheby1(n,pbr,wn,'s')
[z,p,k]=tf2zp(b,a)
[zd,pd,kd]=bilinear(z,p,k,fs)
[num,den]=zp2tf(zd,pd,kd)
figure(1)
freqz(num,den,512,fs)
title('CHEBYCHEV FREQUENCY RESPONSE OF THE GIVEN FILTER')

Output:
Enter the passband edge =500
Enter the stopband edge =750
Enter the passband ripple =0.5
Enter the stopband ripple =30
Enter the sampling frequency =8000

n=6
wn = 3.1416e+003
b = 1.0e+019 *
0 0 0 0 0 0 8.6008
a = 1.0e+019 *

num = 1.0e-004 *
0.0387 0.2321 0.5802 0.7737 0.5802 0.2321 0.0387
den = 1.0000 -5.3378 12.0862 -14.8440 10.4223 -3.9646 0.6382

Program:

Program to design Low pass Chebychev I filter using Impulse Invariance Transformation

pb=input('Enter the passband edge =');


sb=input('Enter the stopband edge =');
pbr=input('Enter the passband ripple =');
sbr=input('Enter the stopband ripple =');

Dept. of ECE, JSSATE, Bengaluru-60 Page 52


Digital Signal Processing Lab (15ECL57) V Semester

fs=input('Enter the sampling frequency =');


pbrad=pb*2*pi;
sbrad=sb*2*pi;
[n,wn]=cheb1ord(pbrad,sbrad,pbr,sbr,'s')
[b,a]=cheby1(n,sbr,wn,'s')
[num,den]=impinvar(b,a,fs)
figure(1)
freqz(num,den,512,fs)
title('CHEBYCHEV I FREQUENCY RESPONSE OF THE GIVEN FILTER')

Output:

Enter the passband edge =1000


Enter the stopband edge =2000
Enter the passband ripple =0.5
Enter the stopband ripple =30
Enter the sampling frequency =8000
n=4
wn = 6.2832e+003
b = 1.0e+012 *
0 0 0 0 6.1638
a = 1.0e+014 *
0.0000 0.0000 0.0000 0.0000 1.9492
num =
1.0e-003 *
0.0000 0.2422 0.9353 0.2402 0

Applications:

1. To build the adaptive process around a linear IIR filter with fewer number of adjustable
coefficients than an FIR filter to achieve a desired response.
2. Acoustic echo cancellation
3. Linear prediction.
4. Adaptive notch filtering.
5. Adaptive differential pulse code modulation.
6. Adaptive array processing.
7. Channel equalization.

Note: Students can choose some of the applications for their presentation.

Dept. of ECE, JSSATE, Bengaluru-60 Page 53


Digital Signal Processing Lab (15ECL57) V Semester

Procedure to Setup Emulator

1. Open CC Studio - Open the Setup icon CCStudio v3.0

2. Import Configuration : The Code Composer Setup opens a configuration file window. This is to
configure my computer with the functional device simulator. ( as shown in Figure below)

Dept. of ECE, JSSATE, Bengaluru-60 Page 54


Digital Signal Processing Lab (15ECL57) V Semester

3. Clear System configuration : Before configuring the system with the simulator or DSP kit clear
the present configuration as shown in figure below

Dept. of ECE, JSSATE, Bengaluru-60 Page 55


Digital Signal Processing Lab (15ECL57) V Semester

4. Select and Configure either the Simulator or DSP Kit :


Follow the following steps to select the simulator/kit

( i ) Select Family C67xx

( ii ) Select Platform dsk for selecting kit

Dept. of ECE, JSSATE, Bengaluru-60 Page 56


Digital Signal Processing Lab (15ECL57) V Semester

( iii ) Select Endianess all for dsk kit

( iii ) Select C6713 DSK and click Import

Dept. of ECE, JSSATE, Bengaluru-60 Page 57


Digital Signal Processing Lab (15ECL57) V Semester

( iii ) Start code composer studio on exit, Click on Yes to start Code Composer Studio

5. Code Composer Studio : Code Composer Studio window is opened

Dept. of ECE, JSSATE, Bengaluru-60 Page 58


Digital Signal Processing Lab (15ECL57) V Semester

6. Select new project : Go to project -- New

7. Name the project : Type in the project name and check other fields according to selection and
click finish.

Dept. of ECE, JSSATE, Bengaluru-60 Page 59


Digital Signal Processing Lab (15ECL57) V Semester

8. Project File Created : Project File Created with many folder within like

9. Select Source File : Select File – New – Source File

Dept. of ECE, JSSATE, Bengaluru-60 Page 60


Digital Signal Processing Lab (15ECL57) V Semester

10. Select Source File : Select File – New – Source File – Type the Source Code and save the code
into project demo with .c extension.

11. Store source file in project : Save the file in the project created only else it does not execute.

Dept. of ECE, JSSATE, Bengaluru-60 Page 61


Digital Signal Processing Lab (15ECL57) V Semester

12. Add source file : To add source, click on source file use the path
C:\CCStudio\Myprojects\project_name\filename.c

13. Add library file : To add library file, click use the path
C:\CCStudio\c6000\cgtools\lib\rts6700.lib – open – .lib get added to library folder

Dept. of ECE, JSSATE, Bengaluru-60 Page 62


Digital Signal Processing Lab (15ECL57) V Semester

14. Add linker command file : To add linker command file, click use the path
C:\CCStudio\tutorial\DSK6713\hello1\hello.cmd – open – .cmd file gets added to source

15. Build the Project : Project --- Build.


16. To load Program : File – Load Program – Debug gets open – Select filename.out file in the
debug Folder – click open – file get loaded on to the kit.
17. To Run : Go to Debug – Run

Dept. of ECE, JSSATE, Bengaluru-60 Page 63


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 9: Linear Convolution of two sequence

Procedure to create new Project:

1. To create project, Go to Project and Select New.

2. Give project name and click on finish.

( Note: Location must be c:\CCStudio_v3.1\MyProjects ).

Dept. of ECE, JSSATE, Bengaluru-60 Page 64


Digital Signal Processing Lab (15ECL57) V Semester

3. Click on File New Source File, To write the Source Code.

Mathematical Formula:
The linear convolution of two continuous time signals x(t) and h(t) is defined by

For discrete time signals x(n) and h(n), is defined by

Where x(n) is the input signal and h(n) is the impulse response of the system.

In linear convolution length of output sequence is,


Length (y(n)) = length(x(n)) + length(h(n)) – 1

Dept. of ECE, JSSATE, Bengaluru-60 Page 65


Digital Signal Processing Lab (15ECL57) V Semester

Program:

#include<stdio.h>
main()
{ int m=4; /*Lenght of i/p samples sequence*/
int n=4; /*Lenght of impulse response Co-efficients */
int i=0,j;
int x[10]={1,2,3,4,0,0,0,0}; /*Input Signal Samples*/
int h[10]={1,2,3,4,0,0,0,0}; /*Impulse Response Co-efficients*/
/*At the end of input sequences pad 'M' and 'N' no. of zero's*/
int *y;
y=(int *)0x0000100;
for(i=0;i<m+n-1;i++)
{
y[i]=0;
for(j=0;j<=i;j++)
y[i]+=x[j]*h[i-j];
}
for(i=0;i<m+n-1;i++)
printf("%d\n",y[i]);
}

Output:

1, 4, 10, 20, 25, 24, 16.

4. Enter the source code and save the file with “.C” extension.

Dept. of ECE, JSSATE, Bengaluru-60 Page 66


Digital Signal Processing Lab (15ECL57) V Semester

5. Right click on source, Select add files to project .. and Choose “.C “ file Saved before.

6. Right Click on libraries and select add files to Project.. and choose

C:\CCStudio_v3.1\C6000\cgtools\lib\rts6700.lib and click open.

Dept. of ECE, JSSATE, Bengaluru-60 Page 67


Digital Signal Processing Lab (15ECL57) V Semester

7. a)Go to Project to Compile .


b) Go to Project to Build.
c) Go to Project to Rebuild All.

Here it
shows
error if any

Dept. of ECE, JSSATE, Bengaluru-60 Page 68


Digital Signal Processing Lab (15ECL57) V Semester

8. Go to file and load program and load “.out” file into the board..

9. Go to Debug and click on run to run the program.

Dept. of ECE, JSSATE, Bengaluru-60 Page 69


Digital Signal Processing Lab (15ECL57) V Semester

10. Observe the output in output window.

Dept. of ECE, JSSATE, Bengaluru-60 Page 70


Digital Signal Processing Lab (15ECL57) V Semester

11. To see the Graph go to View and select time/frequency in the Graph, And give the correct Start
address provided in the program, Display data can be taken as per user.

12. Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left
corner).

Applications :

1. In FIR filters.
2. In Audio, video and speech processing.
3. In filter banks.

Dept. of ECE, JSSATE, Bengaluru-60 Page 71


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 10: Circular Convolution of two sequences.

Circular Convolution:
Let x1(n) and x2(n) are finite duration sequences both of length N with DFT‟s X1(k) and X2(k).
Convolution of two given sequences x1(n) and x2(n) is given by the equation,
x3(n) = IDFT[X3(k)]

X3(k) = X1(k) X2(k)

N-1
x3(n) = ∑ x1(m) x2((n-m))N
m=0

Program:

#include<stdio.h>
int m,n,x[30],h[30],y[30],i,j,temp[30],k,x2[30],a[30];
void main()
{
int *y;
y=(int *)0x0000100;
printf(" enter the length of the first sequence\n");
scanf("%d",&m);
printf(" enter the length of the second sequence\n");
scanf("%d",&n);
printf(" enter the first sequence\n");
for(i=0;i<m;i++)
scanf("%d",&x[i]);
printf(" enter the second sequence\n");
for(j=0;j<n;j++)
scanf("%d",&h[j]);
if(m-n!=0) /*If length of both sequences are not equal*/
{
if(m>n) /* Pad the smaller sequence with zero*/
{
for(i=n;i<m;i++)
h[i]=0;
n=m;
}
for(i=m;i<n;i++)
x[i]=0;
m=n;
}
y[0]=0;
a[0]=h[0];
for(j=1;j<n;j++) /*folding h(n) to h(-n)*/
a[j]=h[n-j];
/*Circular convolution*/
for(i=0;i<n;i++)

Dept. of ECE, JSSATE, Bengaluru-60 Page 72


Digital Signal Processing Lab (15ECL57) V Semester

y[0]+=x[i]*a[i];
for(k=1;k<n;k++)
{
y[k]=0;
/*circular shift*/
for(j=1;j<n;j++)
x2[j]=a[j-1];
x2[0]=a[n-1];
for(i=0;i<n;i++)
{
a[i]=x2[i];
y[k]+=x[i]*x2[i];
}
}
/*displaying the result*/
printf(" the circular convolution is\n");
for(i=0;i<n;i++)
printf("%d ",y[i]);
}

Output:

enter the length of the first sequence


4
enter the length of the second sequence
4
enter the first sequence
4321
enter the second sequence
1111
the circular convolution is
10 10 10 10

Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left
corner).

Applications:
1. To zoom image in camera.

Dept. of ECE, JSSATE, Bengaluru-60 Page 73


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 11: N-Point DFT of a given sequence

Discrete Fourier Transform: The Discrete Fourier Transform is a powerful computation tool
which allows us to evaluate the Fourier Transform X(ejω) on a digital computer or specially
designed digital hardware. Since X(ejω) is continuous and periodic, the DFT is obtained by
sampling one period of the Fourier Transform at a finite number of frequency points. Apart
from determining the frequency content of a signal, DFT is used to perform linear filtering
operations in the frequency domain.

The sequence of N complex numbers x0,..., xN−1 is transformed into the sequence of N complex
numbers X0, ..., XN−1 by the DFT according to the formula:

N-1
X(k) = ∑x(n)e-j2πnk/N k = 0,1, …. N-1
n=0

Program:

//DFT of N-point from lookup table. Output from watch window

#include <stdio.h>
#include <math.h>
#define N 4 //number of data values

float pi = 3.1416;
short x[N] = {1,1,0,0}; //1-cycle cosine
float out[2] = {0,0}; //initialize Re and Im results

void dft(short *x, short k, float *out) //DFT function


{
float sumRe = 0; //initialize real component
float sumIm = 0; //initialize imaginary component
int i = 0;
float cs = 0; //initialize cosine component
float sn = 0; //initialize sine component

for (i = 0; i < N; i++) //for N-point DFT


{
cs = cos(2*pi*(k)*i/N); //real component
sn = sin(2*pi*(k)*i/N); //imaginary component
sumRe = sumRe + x[i]*cs; //sum of real components
sumIm = sumIm - x[i]*sn; //sum of imaginary components
}
out[0] = sumRe; //sum of real components
out[1] = sumIm; //sum of imaginary components
printf("%f %f\n",out[0],out[1]);
}

Dept. of ECE, JSSATE, Bengaluru-60 Page 74


Digital Signal Processing Lab (15ECL57) V Semester

void main()
{
int j;
for (j = 0; j < N; j++)
dft(x, j, out); //call DFT function
}

Output:

2.000000 0.000000
0.999996 -1.000000
0.000000 0.000007
1.000011 1.000000

Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left
corner).

Applications:
1. In filter banks.
2. In Mobiles.
3. In Audio, video and speech processing.

Dept. of ECE, JSSATE, Bengaluru-60 Page 75


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 12: Impulse Response of a first order and second order system.

A discrete time system performs an operation on an input signal based on predefined criteria to
produce a modified output signal. The input signal x(n) is the system excitation, and y(n) is the
system response. The transform operation is shown as,

x(n) y(n) = T[(x(n)]

T
The convolution sum can be represented by, y(n) = x(n) * h(n)

For Example let’s find out an impulse response of a difference equation.


The general form of difference equation is,

M M
y(n) = ∑ak y(n-k) + ∑bk x(n-k)
k=1 k=0

Find out the impulse response of second order difference equation.

Program:

#include<stdio.h>
#define Order 2
#define Len 5
float h[Len] = {0.0,0.0,0.0,0.0,0.0},sum;
void main()
{
int j, k;
float a[Order+1] = {0.1311, 0.2622, 0.1311};
float b[Order+1] = {1, -0.7478, 0.2722};

for(j=0; j<Len; j++)


{
sum = 0.0;
for(k=1; k<=Order; k++)
{
if ((j-k) >= 0)
sum = sum+(b[k]*h[j-k]);
}
if (j <= Order)
h[j] = a[j]-sum;
else
h[j] = -sum;
printf (" %f ",h[j]);
}
}
Dept. of ECE, JSSATE, Bengaluru-60 Page 76
Digital Signal Processing Lab (15ECL57) V Semester

Output:

0.131100 0.360237 0.364799 0.174741 0.031373

For first order difference equation.

Program:
#include<stdio.h>
#define Order 1
#define Len 5
float h[Len] = {0.0,0.0,0.0,0.0,0.0},sum;

void main()
{
int j, k;
float a[Order+1] = {0.1311, 0.2622};
float b[Order+1] = {1, -0.7478};
for(j=0; j<Len; j++)
{
sum = 0.0;
for(k=1; k<=Order; k++)
{
if((j-k)>=0)
sum = sum+(b[k]*h[j-k]);
}
if(j<=Order)
h[j] = a[j]-sum;
else
h[j] = -sum;
printf("%f ", j, h[j]);
}
}

Output:

0.131100 0.360237 0.269385 0.201446 0.150641

Dept. of ECE, JSSATE, Bengaluru-60 Page 77


Digital Signal Processing Lab (15ECL57) V Semester

Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left
corner).

Applications:
1. In testing performance of discrete systems.

Dept. of ECE, JSSATE, Bengaluru-60 Page 78


Digital Signal Processing Lab (15ECL57) V Semester

Experiment 13: Implementation of FIR FILTER

Finite Impulse Response (FIR) Filter: The FIR filters are of non-recursive type, whereby the
present output sample is depending on the present input sample and previous input samples.
The transfer function of a FIR causal filter is given by,
N-1
H(z) = ∑ h(n)z-n
n=0
Where h(n) is the impulse response of the filter.
The Fourier transform of h(n) is
N-1
H(ejw) = ∑h(n)e-jwn
n=0
In the design of FIR filters most commonly used approach is using windows.
The desired frequency response Hd(ejw) of a filter is periodic in frequency and can be expanded
in Fourier series. The resultant series is given by, π
hd(n) = (1/2π) ∫ H(ejw)ejwn dw

And known as Fourier coefficients having infinite length. One possible way of obtaining FIR
filter is to truncate the infinite Fourier series at n = ± [(N-1)/2]
Where N is the length of the desired sequence.
The Fourier coefficients of the filter are modified by multiplying the infinite impulse response
with a finite weighing sequence w(n) called a window.

Where w(n) = w(-n) ≠ 0 for |n| ≤ [(N-1)/2]


=0 for |n| > [(N-1)/2]

After multiplying w(n) with hd(n), we get a finite duration sequence h(n) that satisfies the
desired magnitude response,

h(n) = hd(n) w(n) for |n| ≤ [(N-1)/2]


=0 for |n| > [(N-1)/2]

The frequency response H(ejw) of the filter can be obtained by convolution of Hd(ejw) and
W(ejw) is given by,
π
H(ejw) = (1/2π) ∫ Hd(ejθ) W(ej(w-θ) dθ

H(ejw) = Hd(ejw) * W(ejw)

Program:

#include <stdio.h>
#include "c6713dsk.h"
#include "master.h"
#include "aic23cfg.h"
#include "dsk6713_aic23.h"
Dept. of ECE, JSSATE, Bengaluru-60 Page 79
Digital Signal Processing Lab (15ECL57) V Semester

#include <std.h>
#include <swi.h>
#include <log.h>
#include <c6x.h>
#include <csl.h>
#include <csl_mcbsp.h>

/* Length of sine wave table */


#define SINE_TABLE_SIZE 48

// Delta
/*float filter_Coeff[] ={0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,
0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,
0.00,0.00,0.00,0.00,0.00,0.00,1.00,0.00};*/

// Low Pass Filter


/*float filter_Coeff[] ={2.715297634171146e-003, 2.315819802942924e-004,-1.244493581373643e-
002,7.244364917221401e-003,1.207341716154354e-002, 2.734134166585232e-003,-
1.941706440790678e-002,-1.729098218843226e-002,1.773008730568675e-002,
4.091495174059349e-002,2.113436751136944e-003, -6.788468549771730e-002,-
6.059440700570791e-002,8.970313256448266e-002,3.014572949374625e-001,4.019009454299968e-
001,3.014572949374625e-001, 8.970313256448266e-002,-6.059440700570791e-002,-
6.788468549771730e-002,2.113436751136944e-003, 4.091495174059349e-
002,1.773008730568675e-002, -1.729098218843226e-002,-1.941706440790678e-
002,2.734134166585232e-003,1.207341716154354e-002, 7.244364917221401e-003,-
1.244493581373643e-002, 2.315819802942924e-004,2.715297634171146e-003};*/

// High Pass Filter


Float filter_Coeff[] ={3.294316420702696e-004,3.800020076486443e-003,9.822200806739014e-
003,1.517265313889167e-002, 1.323547007544908e-002,2.635896986048919e-004,-
1.808215737734512e-002,-2.666833013269758e-002,
-1.155354962270025e-002,2.448211866656400e-002,5.534101055783895e-
002,4.424359087198896e-002, -2.922329551555757e-002,-1.473332022689261e-001,-
2.574625659073934e-001,6.976203109125493e-001, -2.574625659073934e-001,-
1.473332022689261e-001,-2.922329551555757e-002,4.424359087198896e-002,
5.534101055783895e-002,2.448211866656400e-002,-1.155354962270025e-002,-
2.666833013269758e-002, -1.808215737734512e-002,2.635896986048919e-
004,1.323547007544908e-002,1.517265313889167e-002, 9.822200806739014e-
003,3.800020076486443e-003,3.294316420702696e-004};

// Pre-generated sine wave data, 16-bit signed samples


int sinetable[SINE_TABLE_SIZE] = {
0x0000, 0x10b4, 0x2120, 0x30fb, 0x3fff, 0x4dea, 0x5a81, 0x658b,
0x6ed8, 0x763f, 0x7ba1, 0x7ee5, 0x7ffd, 0x7ee5, 0x7ba1, 0x76ef,
0x6ed8, 0x658b, 0x5a81, 0x4dea, 0x3fff, 0x30fb, 0x2120, 0x10b4,
0x0000, 0xef4c, 0xdee0, 0xcf06, 0xc002, 0xb216, 0xa57f, 0x9a75,
0x9128, 0x89c1, 0x845f, 0x811b, 0x8002, 0x811b, 0x845f, 0x89c1,
Dept. of ECE, JSSATE, Bengaluru-60 Page 80
Digital Signal Processing Lab (15ECL57) V Semester

0x9128, 0x9a76, 0xa57f, 0xb216, 0xc002, 0xcf06, 0xdee0, 0xef4c


};
DSK6713_AIC23_Config config = { \
0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \
0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\
0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \
0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \
// 0x0014 micin with 0dB boost
0x0014, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ \
0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \
0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */ \
0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \

0x008c, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ \


0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \
};

DSK6713_AIC23_CodecHandle hCodec;
Int32 InitWait =1;
Int32 data;
Int32 Logger[1024];
Int32 LoggerIndex =0;

float in_buffer[100];

main()
{
int i;
LED=0x0;

// Filter Initialization
for( i = 0 ; i < 100; i++ ) in_buffer[i]=0.0;

// Initialize codec
hCodec = DSK6713_AIC23_openCodec(0, &config);
IRQ_globalEnable();
IRQ_enable(IRQ_EVT_RINT1);
IRQ_enable(IRQ_EVT_XINT1);
}

void led(){
static int cc = 1;
LED = cc;

// To Shift Pattern
if (cc == 0x03) cc = 0x05;
else if (cc == 0x05) cc = 0x06;
else if (cc == 0x06) cc = 0x03;
else cc = 0x03;
//To count Binary
Dept. of ECE, JSSATE, Bengaluru-60 Page 81
Digital Signal Processing Lab (15ECL57) V Semester

//cc++; if (cc>0x07) cc = 0x00;

// TO Toggle LED
// *cc ^= 0x07; if ((cc !=0x00) && (cc !=0x07)) cc = 0x07;
}

setpll200M(){

void read(){
int i = 0;
float result;
data=MCBSP_read(DSK6713_AIC23_DATAHANDLE);

if(data>=32768) data= data|0xffff0000;


for( i = 0; i <= 29; i++) in_buffer[i] = in_buffer[i+1];
in_buffer[30]=((float)(data))/16;

result = 0;
for( i = 0 ; i <= 30; i++ ) result += filter_Coeff[i] * in_buffer[i];
data = (Int32)(result*512);
//data = (Int32)(in_buffer[30]*16);
Logger[LoggerIndex++] = data;
if (LoggerIndex == 1024)
LoggerIndex = 0;
}

void write(){
if (InitWait<1000){
InitWait++;
MCBSP_write(DSK6713_AIC23_DATAHANDLE, 0);
MCBSP_write(DSK6713_AIC23_DATAHANDLE, 0);
}
else{
MCBSP_write(DSK6713_AIC23_DATAHANDLE, data);
MCBSP_write(DSK6713_AIC23_DATAHANDLE, data);
}
}

Output:

Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left
corner).

Dept. of ECE, JSSATE, Bengaluru-60 Page 82


Digital Signal Processing Lab (15ECL57) V Semester

. In the graph, chose FFT magnitude as display type we will get Graph B

Dept. of ECE, JSSATE, Bengaluru-60 Page 83


Digital Signal Processing Lab (15ECL57) V Semester

Graph 2:FFT magnitude of FIR filter.

The impulse response of FIR filters.

Dept. of ECE, JSSATE, Bengaluru-60 Page 84


Digital Signal Processing Lab (15ECL57) V Semester

SAMPLE VIVA QUESTIONS AND ANSWER

1. What is the FFT?


The Fast Fourier Transform (FFT) is simply a fast (computationally efficient) way to calculate
the Discrete Fourier Transform (DFT).

2. How does the FFT work?


By making use of periodicities in the sines that are multiplied to do the transforms, the FFT
greatly reduces the amount of calculation required. Here's a little overview.

Functionally, the FFT decomposes the set of data to be transformed into a series of smaller data
sets to be transformed. Then, it decomposes those smaller sets into even smaller sets. At each stage of
processing, the results of the previous stage are combined in special way. Finally, it calculates the DFT
of each small data set. For example, an FFT of size 32 is broken into 2 FFT's of size 16, which are
broken into 4 FFT's of size 8, which are broken into 8 FFT's of size 4, which are broken into 16 FFT's
of size 2. Calculating a DFT of size 2 is trivial.

Here's a slightly more rigorous explanation: It turns out that it is possible to take the DFT of the
first N/2 points and combine them in a special way with the DFT of the second N/2 points to produce a
single N-point DFT. Each of these N/2-point DFTs can be calculated using smaller DFTs in the same
way. One (radix-2) FFT begins, therefore, by calculating N/2 2-point DFTs. These are combined to
form N/4 4-point DFTs. The next stage produces N/8 8-point DFTs, and so on, until a single N-point
DFT is produced

3. How efficient is the FFT?


The DFT takes N^2 operations for N points. Since at any stage the computation required to
combine smaller DFTs into larger DFTs is proportional to N, and there are log2(N) stages (for radix 2),
the total computation is proportional to N * log2(N). Therefore, the ratio between a DFT computation
and an FFT computation for the same N is proportional to N / log2(n). In cases where N is small this
ratio is not very significant, but when N becomes large, this ratio gets very large. (Every time you
double N, the numerator doubles, but the denominator only increases by 1.)

4. Are FFT's limited to sizes that are powers of 2?


No. The most common and familiar FFT's are "radix 2". However, other radices are sometimes
used, which are usually small numbers less than 10. For example, radix-4 is especially attractive
because the "twiddle factors" are all 1, -1, j, or -j, which can be applied without any multiplications at
all.
Also, "mixed radix" FFT's also can be done on "composite" sizes. In this case, you break a non-prime
size down into its prime factors, and do an FFT whose stages use those factors. For example, an FFT of
size 1000 might be done in six stages using radices of 2 and 5, since 1000 = 2 * 2 * 2 * 5 * 5 * 5. It
might also be done in three stages using radix 10, since 1000 = 10 * 10 * 10.

5. What is an FFT "radix"?


The "radix" is the size of an FFT decomposition. In the example above, the radix was 2. For
single-radix FFT's, the transform size must be a power of the radix. In the example above, the size was
32, which is 2 to the 5th power.
6. What are "twiddle factors"?
"Twiddle factors" are the coefficients used to combine results from a previous stage to form
inputs to the next stage

Dept. of ECE, JSSATE, Bengaluru-60 Page 85


Digital Signal Processing Lab (15ECL57) V Semester

7. What is an "in place" FFT?


An "in place" FFT is simply an FFT that is calculated entirely inside its original sample
memory. In other words, calculating an "in place" FFT does not require additional buffer memory (as
some FFT's do.)

8. What is "bit reversal"?


"Bit reversal" is just what it sounds like: reversing the bits in a binary word from left to write.
Therefore the MSB's become LSB's and the LSB's become MSB's. But what does that have to do with
FFT's? Well, the data ordering required by radix-2 FFT's turns out to be in "bit reversed" order, so bit-
reversed indexes are used to combine FFT stages. It is possible (but slow) to calculate these bit-
reversed indices in software; however, bit reversals are trivial when implemented in hardware.
Therefore, almost all DSP processors include a hardware bit-reversal indexing capability (which is one
of the things that distinguishes them from other microprocessors.)

9. What is "decimation in time" versus "decimation in frequency"?


FFT's can be decomposed using DFT's of even and odd points, which is called a Decimation-
In-Time (DIT) FFT, or they can be decomposed using a first-half/second-half approach, which is
called a "Decimation-In-Frequency" (DIF) FFT. Generally, the user does not need to worry which type
is being used

10. What does "FIR" mean?


"FIR" means "Finite Impulse Response".

11 . Why is the impulse response "finite"?


The impulse response is "finite" because there is no feedback in the filter; if you put in an
impulse (that is, a single "1" sample followed by many "0" samples), zeroes will eventually come out
after the "1" sample has made its way in the delay line past all the coefficients.

12. What is the alternative to FIR filters?


DSP filters can also be "Infinite Impulse Response" (IIR). IIR filters use feedback, so when you
input an impulse the output theoretically rings indefinitely.

13. How do FIR filters compare to IIR filters?


Each has advantages and disadvantages. Overall, though, the advantages of FIR filters
outweigh the disadvantages, so they are used much more than IIRs.

14. What are the advantages of FIR Filters (compared to IIR filters)?
Compared to IIR filters, FIR filters offer the following advantages:
They can easily be designed to be "linear phase" (and usually are). Put simply, linear-phase filters
delay the input signal, but don‟t distort its phase.
They are simple to implement. On most DSP microprocessors, the FIR calculation can be done by
looping a single instruction.
They are suited to multi-rate applications. By multi-rate, we mean either "decimation" (reducing the
sampling rate), "interpolation" (increasing the sampling rate), or both. Whether decimating or
interpolating, the use of FIR filters allows some of the calculations to be omitted, thus providing an
important computational efficiency. In contrast, if IIR filters are used, each output must be individually
calculated, even if it that output will discard (so the feedback will be incorporated into the filter).
They have desirable numeric properties. In practice, all DSP filters must be implemented using "finite-
precision" arithmetic, that is, a limited number of bits. The use of finite-precision arithmetic in IIR
Dept. of ECE, JSSATE, Bengaluru-60 Page 86
Digital Signal Processing Lab (15ECL57) V Semester

filters can cause significant problems due to the use of feedback, but FIR filters have no feedback, so
they can usually be implemented using fewer bits, and the designer has fewer practical problems to
solve related to non-ideal arithmetic.
They can be implemented using fractional arithmetic. Unlike IIR filters, it is always possible to
implement a FIR filter using coefficients with magnitude of less than 1.0. (The overall gain of the FIR
filter can be adjusted at its output, if desired.) This is an important consideration when using fixed-
point DSP's, because it makes the implementation much simpler.

15. What are the disadvantages of FIR Filters (compared to IIR filters)?
Compared to IIR filters, FIR filters sometimes have the disadvantage that they require more
memory and/or calculation to achieve a given filter response characteristic. Also, certain responses are
not practical to implement with FIR filters.

16. What terms are used in describing FIR filters?


Impulse Response - The "impulse response" of a FIR filter is actually just the set of FIR
coefficients. (If you put an "impulse" into a FIR filter which consists of a "1" sample followed by
many "0" samples, the output of the filter will be the set of coefficients, as the 1 sample moves past
each coefficient in turn to form the output.)
Tap - A FIR "tap" is simply a coefficient/delay pair. The number of FIR taps, (often designated
as "N") is an indication of 1) the amount of memory required to implement the filter, 2) the number of
calculations required, and 3) the amount of "filtering" the filter can do; in effect, more taps means more
stop band attenuation, less ripple, narrower filters, etc.)
Multiply-Accumulate (MAC) - In a FIR context, a "MAC" is the operation of multiplying a
coefficient by the corresponding delayed data sample and accumulating the result. FIRs usually require
one MAC per tap. Most DSP microprocessors implement the MAC operation in a single instruction
cycle.
Transition Band - The band of frequencies between passband and stop band edges. The
narrower the transition band, the more taps are required to implement the filter. (A "small" transition
band results in a "sharp" filter.)
Delay Line - The set of memory elements that implement the "Z^-1" delay elements of the FIR
calculation.
Circular Buffer - A special buffer which is "circular" because incrementing at the end causes it
to wrap around to the beginning, or because decrementing from the beginning causes it to wrap around
to the end. Circular buffers are often provided by DSP microprocessors to implement the "movement"
of the samples through the FIR delay-line without having to literally move the data in memory. When a
new sample is added to the buffer, it automatically replaces the oldest one.

17. What is a linear phase filter?


"Linear Phase" refers to the condition where the phase response of the filter is a linear (straight-
line) function of frequency (excluding phase wraps at +/- 180 degrees). This results in the delay
through the filter being the same at all frequencies. Therefore, the filter does not cause "phase
distortion" or "delay distortion". The lack of phase/delay distortion can be a critical advantage of FIR
filters over IIR and analog filters in certain systems, for example, in digital data modems.

18. What is the delay of a linear-phase FIR?


The formula is simple: given a FIR filter which has N taps, the delay is: (N - 1) / (2 * Fs),
where Fs is the sampling frequency. So, for example, a 21 tap linear-phase FIR filter operating at a 1
kHz rate has delay: (21 - 1) / (2 * 1 kHz)=10 milliseconds

Dept. of ECE, JSSATE, Bengaluru-60 Page 87


Digital Signal Processing Lab (15ECL57) V Semester

19. What is the alternative to linear phase?


Non-linear phase, of course. ;-) Actually, the most popular alternative is "minimum phase".
Minimum-phase filters (which might better be called "minimum delay" filters) have less delay than
linear-phase filters with the same amplitude response, at the cost of a non-linear phase characteristic,
a.k.a. "phase distortion".
A lowpass FIR filter has its largest-magnitude coefficients in the center of the impulse response. In
comparison, the largest-magnitude coefficients of a minimum-phase filter are nearer to the beginning.

20. What is the Z transform of a FIR filter?

For an N-tap FIR filter with coefficients h(k), whose output is described by:

y(n)=h(0)x(n) + h(1)x(n-1) + h(2)x(n-2) + ... h(N-1)x(n-N-1),

the filter's Z transform is:

H(z)=h(0)z-0 + h(1)z-1 + h(2)z-2 + ... h(N-1)z-(N-1) , or

21. What is the frequency response formula for a FIR filter?

H(j)=h(0)e-j0 + h(1)e-j1 + h(2)e-j2 + ... h(N-1)e-j(N-1) , or

Using Euler's identity, e-ja=cos(a) - jsin(a), we can write H() in rectangular form as:

H(j)=h(0)[cos(0) - jsin(0)] + h(1)[cos(1) - jsin(1)] + ... h(N-1)[cos((N-1)) - jsin((N-1))] , or

22.Can I calculate the frequency response of a FIR using the Discrete Fourier Transform (DFT)?
Yes. For an N-tap FIR, you can get N evenly-spaced points of the frequency response by doing
a DFT on the filter coefficients. However, to get the frequency response of the filter at any arbitrary
frequency (that is, at frequencies between the DFT outputs), you will need to use the formula above.

23. What is the DC gain of a FIR filter?


Consider a DC (zero Hz) input signal consisting of samples which each have value 1.0. After
the FIR's delay line had filled with the 1.0 samples, the output would be the sum of the coefficients.
Therefore, the gain of a FIR filter at DC is simply the sum of the coefficients.
This intuitive result can be checked against the formula above. If we set  to zero, the cosine term is
always 1, and the sine term is always zero, so the frequency response becomes:

Dept. of ECE, JSSATE, Bengaluru-60 Page 88


Digital Signal Processing Lab (15ECL57) V Semester

24. Are FIR filters inherently stable?


Yes. Since they have no feedback elements, any bounded input results in a bounded output.

25. What makes the numerical properties of FIR filters "good"?


Again, the key is the lack of feedback. The numeric errors that occur when implementing FIR
filters in computer arithmetic occur separately with each calculation; the FIR doesn't "remember" its
past numeric errors. In contrast, the feedback aspect of IIR filters can cause numeric errors to
compound with each calculation, as numeric errors are fed back.
The practical impact of this is that FIRs can generally be implemented using fewer bits of
precision than IIRs. For example, FIRs can usually be implemented with 16 bits, but IIRs generally
require 32 bits, or even more.

26. Why are FIR filters generally preferred over IIR filters in multirate (decimating and
interpolating) systems?
Because only a fraction of the calculations that would be required to implement a decimating or
interpolating FIR in a literal way actually needs to be done.
Since FIR filters do not use feedback, only those outputs which are actually going to be used have to
be calculated. Therefore, in the case of decimating FIRs (in which only 1 of N outputs will be used),
the other N-1 outputs don't have to be calculated. Similarly, for interpolating filters (in which zeroes
are inserted between the input samples to raise the sampling rate) you don't actually have to multiply
the inserted zeroes with their corresponding FIR coefficients and sum the result; you just omit the
multiplication-additions that are associated with the zeroes (because they don't change the result
anyway.)
In contrast, since IIR filters use feedback, every input must be used, and every input must be calculated
because all inputs and outputs contribute to the feedback in the filter.
27. What are the methods of designing FIR filters?
The three most popular design methods are (in order):
Parks-McClellan: The Parks-McClellan method (inaccurately called "Remez" by Matlab) is
probably the most widely used FIR filter design method. It is an iteration algorithm that accepts filter
specifications in terms of passband and stopband frequencies, passband ripple, and stopband
attenuation. The fact that you can directly specify all the important filter parameters is what makes this
method so popular. The PM method can design not only FIR "filters" but also FIR "differentiators" and
FIR "Hilbert transformers".
Windowing:. In the windowing method, an initial impulse response is derived by taking the
Inverse Discrete Fourier Transform (IDFT) of the desired frequency response. Then, the impulse
response is refined by applying a data window to it.
Direct Calculation: The impulse responses of certain types of FIR filters (e.g. Raised Cosine
and Windowed Sinc) can be calculated directly from formulas.
28. What are the disadvantages of IIR filters (compared to FIR filters)?
They are more susceptible to problems of finite-length arithmetic, such as noise generated by
calculations, and limit cycles. (This is a direct consequence of feedback: when the output isn't
computed perfectly and is fed back, the imperfection can compound.)
They are harder (slower) to implement using fixed-point arithmetic.
They don't offer the computational advantages of FIR filters for multirate.
Dept. of ECE, JSSATE, Bengaluru-60 Page 89
Digital Signal Processing Lab (15ECL57) V Semester

Additional Viva Questions

(Answers to be prepared by students)

1 What is the difference between analog and digital filters?

2. What is the difference between Butterworth and chebyscheve filter.

3. State sampling theorem

4. What are the characteristics of Butterworth Filter?

5. What are the characteristics of chebyscheve filter?

6. Mention the different methods of designing of FIR filter

7. Mention the different methods of designing of IIR filter

8. Name any 4 properties of DFT

9. What are the advantages of DSP over ASP?

10 .Write the Block diagram of Digital signal processing

11. What are the limitations of DSP?

12. Mention the applications of DSP

13. What is the difference between Floating point and Fixed point DSP processor?

14. Tell me about CCS (Code composer studio)

15. Abberivate JTAG

16. What is Emulator?

17. What is the difference between Frequency domain and time domain approach.

18. What is autocorrelation?

19. What is cross correlation?

20. What is correlation?

Dept. of ECE, JSSATE, Bengaluru-60 Page 90


Digital Signal Processing Lab (15ECL57) V Semester

QUESTION BANK
PART A
MATLAB Programs

1. Write a MATLAB program to verify the sampling theorem for the following three cases
 Sampling
 Under sampling
 Over sampling

2. Write a MATLAB program to compute the N-Point DFT of the sequence


x(n) = {1,1,1,1} taking N=4 and N=8.

3. Write a MATLAB program to perform the linear convolution of the sequences given
x1(n) = {1, 2, 3, 4, 5} x2(n) = {2, 3, 4} & verify linear, distributive & associative
property.

4. Write a MATLAB program to perform circular convolution of the given sequences


x1(n) = {1, 2, 3, 4} x2(n) = {4, 3, 2, 2} & verify linear, distributive & associative
property.

5. Write a MATLAB program to perform circular convolution of given two sequences


x1(n) = {2, 3, 4, 0} and x2(n) = {2, 1, 0, 0} by using DFT and IDFT method.

6. Write a MATLAB program to compute the autocorrelation of the given sequence and
verify its properties. X = {1, 2, 3, 6, 2, 4}

7. Write a MATLAB program to find the cross correlation of the given two sequences
x = {1, 2, 4, 6, 5} and y = {1, 3, 2, 1, 4}

8. Write a MATLAB program to solve the given difference equation


y (n) – 3/2 y (n-1) + 1/2 y (n-2) = x (n). Given x(n) = (1/4)n y(n).
Assume initial conditions as y(-1) = 4,y(-2) = 10.

9. Using MATLAB design an IIR filter with pass band edge frequency at 1500Hz and stop
band edge at 2000Hz for a sampling frequency of 8000Hz.passband attenuation is 1dB
and stop band attenuation is 15dB. Use butter worth prototype design and bilinear
transformation.

10. Using MATLAB design an FIR filter with pass band edge frequency at 1500Hz and stop
band edge at 2000Hz for a sampling frequency of 8000Hz.passband attenuation is 1dB
and stop band attenuation is 15dB. Use chebyshev prototype design and bilinear
transformation.

11. Write a MATLAB program to verify the following DFT property


a) Linearity & b) Parsevals Theroem
Dept. of ECE, JSSATE, Bengaluru-60 Page 91
Digital Signal Processing Lab (15ECL57) V Semester

12. Write a MATLAB program to compute the DFT of Square pulse & Sine Function.

PART B

Using DSP KIT

1. Using DSP Processor find out the Discrete Time Convolution of the sequences
x(n)={1 2 3 4 5 6} and h(n)={1 2 3 4}, verify the results graphically.

2. Using DSP Processor perform Circular Convolution of the given.

3. Using DSP Processor compute the response of the system whose co-efficients are
a0=0.1311, a1=0.2622, a2=0.1311 and b0=1, b1= -0.7478, b2=0.2722, when the input is a
unit impulse signal.

4. Using DSP Processor compute the DFT of an N – Point sequence from a lookup table.

5. Using DSP Processor Demonstrate design of FIR filter to meet the given specification.

Dept. of ECE, JSSATE, Bengaluru-60 Page 92


Digital Signal Processing Lab (15ECL57) V Semester

Related To MATLAB

1. What is MATLAB?
MATLAB is a commercial software package written by The Math works. Quoting from their
web page:
Numeric computation, technical graphics and visualization, and an intuitive programming language for
applications in engineering and science
MATLAB is a complete environment for high-level programming, as well as interactive data analysis.
MATLAB excels at numerical computations, especially when dealing with vectors or matrices of data.
Symbolic math is available through an add-on toolbox that uses a Maple kernel.

What toolboxes are currently available from The Math Works?


The following list includes toolboxes currently offered by The MathWorks. For more info check
ftp.mathworks.com in /pub/product-info
Signal Processing Toolbox.
This is a toolbox for digital signal processing (time series analysis). It includes functions for the design
and analysis of digital filters, like Butterworth, Elliptic, and Parks-McClellan, and for FFT analysis
(power spectrum estimation). It also includes some 2-dimensional signal processing capabilities.
Control System Toolbox.
This is a toolbox for control system design and analysis. It supports transfer function and state-space
forms (continuous/discrete time, frequency domain). Function for step, impulse, arbitrary input
responses, as well as Bode, Nyquist, and Nichols plots. Design with root-locus, pole-placement, and
LQR optimal control.
System Identification Toolbox.
This is a toolbox for parametric modelling. Identified models are in transfer function form (either z-
transform or Laplace transform) and state-space form (e.g., ARMA models or Box-Jenkins models).
Optimization Toolbox.
This is a toolbox for linear and nonlinear optimization and supports unconstrained and constrained
minimization, minimax, nonlinear least squares, multi-objective, and semi-infinite optimization, linear
programming, quadratic programming and the solution of non-linear equations.
Spline Toolbox.
This is a toolbox for working with splines and is typically used for curve fitting, solution of function
equations and functional approximation.
Robust-Control Toolbox.
This is a toolbox for robust control system design and supports LQG/loop transfer recovery, H2, H0,
and mu- control synthesis, singular value frequency response, and model reduction.
Neural Net Toolbox.
This is a toolbox for designing and simulating neural networks and supports implementation of the
perceptron learning rule, the Widrow-Hoff rule, and several variations of the backpropagation rule.
Transfer functions included are hard limit, linear, logistic & hypertangent sigmoid.
Delta Toolbox.
This is a toolbox for analysis using the delta transform, an approach to unifying continuous and
discrete systems theory without use of the Z-transform. It is available free to purchasers of "Digital
Control and Estimation: A Unified Approach," by Graham Goodwin and Rick Middleton.
Image Processing Toolbox.
The Image Processing Toolbox provides an environment for image processing and analysis. Images are
matrices (surprised?). Functions include linear and nonlinear filtering; image restoration; image
enhancement; image analysis and statistics; color, geometric, and morphological operations 2-D
transforms; and 2D FIR filter design and frequency response.
Dept. of ECE, JSSATE, Bengaluru-60 Page 93
Digital Signal Processing Lab (15ECL57) V Semester

Symbolic Math Toolbox.


The Symbolic Math Toolbox contains functions for symbolic algebra, exact linear algebra, variable
precision arithmetic, equation solving, and special mathematical functions. Its underlying
computational engine is the kernel of Maple. The Extended Symbolic Math Toolbox augments the
functionality to include Maple programming features and specialized libraries.
Statistics Toolbox.
The Statistics Toolbox provides statistical data analysis, modeling, and Monte Carlo simulation;
building-blocks for creating your own special-purpose statistical tools; and GUI tools for exploring
fundamental concepts in statistics and probability. Functionality covers descriptive, inferential, and
graphical statistics, and linear models as well as interactive graphics for dynamic visualization of
functions, data, and probability distributions.

How can I change the default window size, colors, etc. in MATLAB 4?
Some Examples
set(0,'DefaultFigurePosition',[5 5 505 405])
set(0,'DefaultFigureColor',[0,0,0]) %% N.B this has side effects.
set(0,'DefaultAxesFontName','times')
set(0,'DefaultTextFontName','times')
set(0,'DefaultAxesFontSize',12)
set(0,'DefaultTextFontSize',12)

What are the Uses of MATLAB?


1. Simple calculations
2. Plotting and analyzing mathematical relationships (2D and 3D)
3. List & Matrix Operations
4. Writing script files (a type of programming)
5. Symbolic manipulation of equations
6. Advanced visualization, animation and GUI interface tools

Study all the MATLAB Commands (Quice reference Go through Appendix)

What is the difference between a DSP and a microprocessor?


The essential difference between a DSP and a microprocessor is that a DSP processor has
features designed to support high-performance, repetitive, numerically intensive tasks. In contrast,
general-purpose processors or microcontrollers (GPPs/MCUs for short) are either not specialized for a
specific kind of applications (in the case of general-purpose processors), or they are designed for
control-oriented applications (in the case of microcontrollers). Features that accelerate performance in
DSP applications include:
Single-cycle multiply-accumulate capability; high-performance DSPs often have two
multipliers that enable two multiply-accumulate operations per instruction cycle; some DSP have four
or more multipliers
Specialized addressing modes, for example, pre- and post-modification of address pointers, circular
addressing, and bit-reversed addressing.
Most DSPs provide various configurations of on-chip memory and peripherals tailored for DSP
applications. DSPs generally feature multiple-access memory architectures that enable DSPs to
complete several accesses to memory in a single instruction cycle.
Specialized execution control. Usually, DSP processors provide a loop instruction that allows tight
loops to be repeated without spending any instruction cycles for updating and testing the loop counter
or for jumping back to the top of the loop.

Dept. of ECE, JSSATE, Bengaluru-60 Page 94


Digital Signal Processing Lab (15ECL57) V Semester

DSP processors are known for their irregular instruction sets, which generally allow several
operations to be encoded in a single instruction. For example, a processor that uses 32-bit instructions
may encode two additions, two multiplications, and four 16-bit data moves into a single instruction. In
general, DSP processor instruction sets allow a data move to be performed in parallel with an
arithmetic operation. GPPs/MCUs, in contrast, usually specify a single operation per instruction.
While the above differences traditionally distinguish DSPs from GPPs/MCUs, in practice it is
not important what kind of processor you choose. What is really important is to choose the processor
that is best suited for your application; if a GPP/MCU is better suited for your DSP application than a
DSP processor, the processor of choice is the GPP/MCU. It is also worth noting that the difference
between DSPs and GPPs/MCUs is fading: many GPPs/MCUs now include DSP features, and DSPs are
increasingly adding microcontroller features.

What are the available DSP chips and chip architectures?


The "big four" programmable DSP chip manufacturers are Texas Instruments, with the
TMS320C2000, TMS320C5000, and TMS320C6000 series of chips; Freescale, with the DSP56300,
DSP56800, and MSC8100 (StarCore) series; Agere Systems (formerly Lucent Technologies), with the
DSP16000 series; and Analog Devices, with the ADSP-2100 and ADSP-21000 ("SHARC") series

Agere Systems (formerly Lucent Technologies)


DSP16xxx:
100 to 170 MHz 16-bit fixed-point DSP. The DSP16000 core features two multipliers with
SIMD-like capabilities, a 20-bit address bus, a 32-bit address bus, and eight 40-bit
accumulators. The chips feature two serial ports and two timers.

The first-generation processor, the DSP16210, contains a single DSP16000 core and 120 KB of
internal RAM. The second-generation DSP16410 incorporates two DSP16000 cores and 386
KB of internal RAM.

Analog Devices
ADSP-21xx:
10 to 80 MHz 16-bit fixed point DSPs; 40-bit accumulator; 24-bit instructions. Large number
of family members with different configurations of on-chip memory and serial ports, timers, and host
ports. ADSP-21mspxx members include an on-chip codec.

ADSP-219x:
160 MHz 16-bit fixed point DSPs; 40-bit accumulator; 24-bit instructions. Based on the ADSP-
21xx family, and is is mostly, but not completely, assembly source-code upward compatible with the
ADSP-21xx Adds new addressing modes and an instruction cache, expands address space, and
lengthens pipeline (six stages compared to three on the ADSP21xx). Family includes members
containing multiple ADSP-219x cores.

ADSP-21xxx ("SHARC"):
33 to 100 MHz floating-point DSP; Supports 32-bit fixed-point, IEEE format 32-bit floating-
point, and 40-bit floating-point; 40-bit registers plus an 80-bit accumulator that can be divided into two
32-bit registers and a 16-bit register.
The first-generation SHARC, the ADSP-2106x, features a single data path, a 32-bit address
bus, and 40-bit data bus. Versions are available with up to 512 KB of on-chip memory, up to six
communication ports, and up to 10 DMA channels.

Dept. of ECE, JSSATE, Bengaluru-60 Page 95


Digital Signal Processing Lab (15ECL57) V Semester

The second-generation ADSP-2116x has two parallel data paths, a 32-bit address bus, and a 64-
bit data bus. Versions are available with up to 512 KB of on-chip memory; up to six communication
ports, and up to 14 DMA channels.
Analog Devices also sells the AD14000 series, which contain four ADSP-2106x SHARC
processors in a single-chip package.

ADSP-2153x:
200 to 300 MHz 16-bit fixed point DSPs that can execute two MAC instructions per cycle;
based on the ADI/Intel MSA core. Uses a mix of 16-, 32-, and 64-bit instructions. Features include
ability to operate over a wide range of frequencies and voltages.

Free scale
DSP563xx:
66 to 160 MHz 24-bit fixed-point DSP; most family members have 24-bit address and data
busses. The DSP563xx also features 56-bit accumulators (2), timers, serial interface, host
interface port. The DSP56307 and DSP56311 contain a filter co-processor. Up to 1 MB of
internal RAM.

DSP568xx:
40 MHz 16-bit fixed point DSP; 36-bit accumulators (2), three internal address buses (two 16-
bit, one 19-bit) and one 16-bit external address bus; three 16-bit internal data buses, one 16-bit
external data bus; serial ports, timers. 4-12 KB of internal RAM. Most family members include
an on-chip A/D.

DSP5685x:
160 MHz 16-bit fixed point DSP based on the DSP568xx. Adds an exponent detector and two
accumulators, extends shifter and the logic unit to 32 bits, and widens internal address and data
buses. The DSP5685x uses a 1X master clock rate rather than the 2X master clock rate used by
the DSP568xx.

MSC81xx:
The 300 MHz MSC8101 is the first processor based on the StarCore SC140 core. It contains
four parallel ALU units that can execute up to four MAC operations in a single clock cycle.
The MSC8101 uses variable-length instructions. Features include: 512 KB on-chip RAM; 16
DMA channels; an on-chip filter co-processor; and interfaces for ATM, Ethernet, E1/T1 and
E3/T3, and the PowerPC bus.

Texas Instruments

TMS320C2xxx:
20-40 MHz 16-bit fixed-point DSPs oriented toward low-cost control applications; 16 bit data,
32 bit registers. The family members have a variety of peripherals, such as A/D converters, 41
I/O pins, and 16 PWM outputs. A variety of RAM and ROM configurations are available
TI also sells the TMS320C2x family, an older version of the chip with fewer features.

Dept. of ECE, JSSATE, Bengaluru-60 Page 96


Digital Signal Processing Lab (15ECL57) V Semester

TMS320C3x:
33-75 MHz floating point DSPs; 32-bit floating-point, 24-bit fixed-point data, 40-bit registers;
DMA controller; serial ports; some support for multi-processor arrays. Various ROM and RAM
configurations.

TMS320C54xx:
40 to 160 MHz 16-bit fixed-point DSPs with a large number of specialized instructions. Many
family members; the processors differ in configuration of on-chip ROM/RAM, serial ports,
autobuffered serial ports, host ports, and time-division multiplexed ports. On-chip RAM ranges
from 10 KB to over 1 MB.

TMS320C55xx:
144 to 200 MHz dual-ALU variant of the TMS320C54xx that can execute two MAC
instructions per cycle. Variable instruction word width. Features include up to 320 KB internal
RAM; 6 DMA channels; 2 serial ports; and 2 timers.

TMS320C62xx:
150-300 MHz 16-bit fixed-point DSP with VLIW (very large instruction word), load/store
architecture; 32 32-bit registers; very deep pipeline; two multipliers, ALUs, and shifters; cache.

TMS320C64xx:
400-600 MHz 16-bit fixed-point DSP based on the TMS320C62xx. Adds SIMD support to
most execution units, including extensive 8-bit SIMD support. Also doubles data bandwidth
and increases size of on-chip memory.

TMS320C67xx:
100-167 MHz 32-bit and 64-bit IEEE-754 floating-point DSP with VLIW (very large
instruction word), load/store architecture; 32 32-bit registers; very deep pipeline; two
multipliers, ALUs, and shifters; cache

Dept. of ECE, JSSATE, Bengaluru-60 Page 97


Digital Signal Processing Lab (15ECL57) V Semester

Matlab Commands List

abs Absolute value

acker Compute the K matrix to place the poles of A-BK, see also place

axis Set the scale of the current plot, see also plot, figure

bode Draw the Bode plot, see also logspace, margin, nyquist1

c2dm Continuous system to discrete system

clf Clear figure (use clg in Matlab 3.5)

conv Convolution (useful for multiplying polynomials), see also deconv

ctrb The controllability matrix, see also obsv

deconv Deconvolution and polynomial division, see also conv

det Find the determinant of a matrix

dimpulse Impulse response of discrete-time linear systems, see also dstep

dlqr Linear-quadratic regulator design for discrete-time systems, see also lqr

dlsim Simulation of discrete-time linear systems, see also lsim

dstep Step response of discrete-time linear systems, see also stairs

eig Compute the eigenvalues of a matrix

eps Matlab's numerical tolerance

feedback Feedback connection of two systems.

figure Create a new figure or redefine the current figure, see also subplot, axis

for For, next loop

format Number format (significant digits, exponents)

function Creates function m-files

grid Draw the grid lines on the current plot

gtext Add a piece of text to the current plot, see also text

help HELP!

hold Hold the current graph, see also figure

Dept. of ECE, JSSATE, Bengaluru-60 Page 98


Digital Signal Processing Lab (15ECL57) V Semester

if Conditionally execute statements

imag Returns the imaginary part of a complex number, see also real

impulse Impulse response of continuous-time linear systems, see also step, lsim, dlsim

input Prompt for user input

inv Find the inverse of a matrix

Generate grid lines of constant damping ratio (zeta) and settling time (sigma), see
jgrid
also sgrid, sigrid, zgrid

legend Graph legend

length Length of a vector, see also size

linspace Returns a linearly spaced vector

lnyquist1 Produce a Nyquist plot on a logarithmic scale, see also nyquist1

log natural logarithm, also log10: common logarithm

loglog Plot using log-log scale, also semilogx/semilogy

logspace Returns a logarithmically spaced vector

lqr Linear quadratic regulator design for continuous systems, see also dlqr

lsim Simulate a linear system, see also step, impulse, dlsim.

margin Returns the gain margin, phase margin, and crossover frequencies, see also bode

norm Norm of a vector

Draw the Nyquist plot, see also lnyquist1. Note this command was written to
nyquist1
replace the Matlab standard command nyquist to get more accurate Nyquist plots.

obsv The observability matrix, see also ctrb

ones Returns a vector or matrix of ones, see also zeros

place Compute the K matrix to place the poles of A-BK, see also acker

plot Draw a plot, see also figure, axis, subplot.

poly Returns the characteristic polynomial

polyadd Add two different polynomials

polyval Polynomial evaluation

Dept. of ECE, JSSATE, Bengaluru-60 Page 99


Digital Signal Processing Lab (15ECL57) V Semester

print Print the current plot (to a printer or postscript file)

pzmap Pole-zero map of linear systems

rank Find the number of linearly independent rows or columns of a matrix

real Returns the real part of a complex number, see also imag

rlocfind Find the value of k and the poles at the selected point

rlocus Draw the root locus

roots Find the roots of a polynomial

rscale Find the scale factor for a full-state feedback system

Set(gca,'Xtick',xticks,'Ytick',yticks) to control the number and spacing of tick


set
marks on the axes

series Series interconnection of Linear time-independent systems

Generate grid lines of constant damping ratio (zeta) and natural frequency (Wn),
sgrid
see also jgrid, sigrid, zgrid

sigrid Generate grid lines of constant settling time (sigma), see also jgrid, sgrid, zgrid

size Gives the dimension of a vector or matrix, see also length

sqrt Square root

ss Create state-space models or convert LTI model to state space, see also tf

ss2tf State-space to transfer function representation, see also tf2ss

ss2zp State-space to pole-zero representation, see also zp2ss

stairs Stairstep plot for discreste response, see also dstep

step Plot the step response, see also impulse, lsim, dlsim.

subplot Divide the plot window up into pieces, see also plot, figure

text Add a piece of text to the current plot, see also title, xlabel, ylabel, gtext

tf Creation of transfer functions or conversion to transfer function, see also ss

tf2ss Transfer function to state-space representation, see also ss2tf

tf2zp Transfer function to Pole-zero representation, see also zp2tf

title Add a title to the current plot

Dept. of ECE, JSSATE, Bengaluru-60 Page 100


Digital Signal Processing Lab (15ECL57) V Semester

Returns the bandwidth frequency given the damping ratio and the rise or settling
wbw
time.

Add a label to the horizontal/vertical axis of the current plot, see also title, text,
xlabel/ylabel
gtext

zeros Returns a vector or matrix of zeros

Generates grid lines of constant damping ratio (zeta) and natural frequency (Wn),
zgrid
see also sgrid, jgrid, sigrid

zp2ss Pole-zero to state-space representation, see also ss2zp

zp2tf Pole-zero to transfer function representation, see also tf2zp

Dept. of ECE, JSSATE, Bengaluru-60 Page 101


Digital Signal Processing Lab (15ECL57) V Semester

How to start MATLAB

PC: Choose the submenu "Programs" from the "Start" menu. From the "Programs" menu, open the
"MATLAB" submenu. From the "MATLAB" submenu, choose "MATLAB".

The MATLAB environment

Note: From now on an instruction to press a certain key will be denoted by < >, e.g., pressing the enter
key will be denoted as <enter>. Commands that should be typed at the prompt, will be written in
courier font.

The MATLAB environment (on most computer systems) consists of menus, buttons and a writing area
similar to an ordinary word processor. There are plenty of help functions that you are encouraged to
use. The writing area that you will see when you start MATLAB, is called the command window. In
this window you give the commands to MATLAB. For example, when you want to run a program you
have written for MATLAB you start the program in the command window by typing its name at the
prompt. The command window is also useful if you just want to use MATLAB as a scientific
calculator or as a graphing tool. If you write longer programs, you will find it more convenient to write
the program code in a separate window, and then run it in the command window

In the command window you will see a prompt that looks like >> . You type your commands
immediately after this prompt. Once you have typed the command you wish MATLAB to perform,
press <enter>. If you want to interupt a command that MATLAB is running, type <ctrl> + <c>.

The commands you type in the command window are stored by MATLAB and can be viewed in the
Command History window. To repeat a command you have already used, you can simply double-click
on the command in the history window, or use the <up arrow> at the command prompt to iterate
through the commands you have used until you reach the command you desire to repeat.

Useful functions and operations in MATLAB


Using MATLAB as a calculator is easy.

Example: Compute 5 sin(2.53-pi)+1/75. In MATLAB this is done by simply typing

5*sin(2.5^(3-pi))+1/75

at the prompt. Be careful with parantheses and don't forget to type * whenever you multiply!

Note that MATLAB is case sensitive. This means that MATLAB knows a difference between letters
written as lower and upper case letters. For example, MATLAB will understand sin(2) but will not
understand Sin(2).

Here is a table of useful operations, functions and constants in MATLAB.

Operation, function or constant MATLAB command


+ (addition) +
- (subtraction) -

Dept. of ECE, JSSATE, Bengaluru-60 Page 102


Digital Signal Processing Lab (15ECL57) V Semester

× (multiplication) *
/ (division) /
|x| (absolute value of x) abs(x)
square root of x sqrt(x)
x
e exp(x)
ln x (natural log) log(x)
log10 x (base 10 log) log10(x)
sin x sin(x)
cos x cos(x)
tan x tan(x)
cot x cot(x)
arcsin x asin(x)
arccos x acos(x)
arctan x atan(x)
arccot x acot(x)
n! (n factorial) gamma(n+1)
e (2.71828...) exp(1)
 (3.14159265...) pi
i (imaginary unit, sqrt(-1)) i

Obtaining Help on MATLAB commands


To obtain help on any of the MATLAB commands, you simply need to type help <command>
at the command prompt. For example, to obtain help on the gamma function, we type at the command
prompt:
help gamma
Try this now. You may also get help about commands using the "Help Desk", which can be accessed
by selecting the MATLAB Help option under the Help menu.
Note that the description MATLAB returns about the command you requested help on contains the
command name in ALL CAPS. This does not mean that you use this command by typing it in ALL
CAPS. In MATLAB, you almost always use all lower case letters when using a command.

Variables in MATLAB
We can easily define our own variables in MATLAB. Let's say we need to use the value of
3.5sin(2.9) repeatedly. Instead of typing 3.5*sin(2.9)over and over again, we can denote this variable
as x by typing the following:

x=3.5*sin(2.9)

(Please try this in MATLAB.) Now type

x+1

Dept. of ECE, JSSATE, Bengaluru-60 Page 103


Digital Signal Processing Lab (15ECL57) V Semester

and observe what happens. Note that we did not need to declare x as a variable that is supposed
to hold a floating point number as we would need to do in most programming languages.

Often, we may not want to have the result of a calculation printed-out to the command window. To
supress this output, we put a semi-colon at the end of the command; MATLAB still performs the
command in "the background". If you defined x as above, now type

y=2*x;

y and observe what happened.

In many cases we want to know what variables we have declared. We can do this by typing whos.
Alternatively, we can view the values by openning the "Workspace" window. This is done by selecting
the Workspace option from the View menu. If you want to erase all variables from the MATLAB
memory, type clear. To erase a specific variable, say x, type clear x. To clear two specific variables,
say x and y, type clear x y, that is separate the different variables with a space. Variables can also be
cleared by selecting them in the Workspace window and selecting the delete option.

Vectors and matrices in MATLAB

We create a vector in MATLAB by putting the elements within [] brackets.

Example: x=[ 1 2 3 4 5 6 7 8 9 10]

We can also create this vector by typing x=1:10. The vector (1 1.1 1.2 1.3 1.4 1.5) can be created by
typing x=[ 1 1.1 1.2 1.3 1.4 1.5 ] or by typing x=1:0.1:1.5.

Matrices can be created according to the following example. The matrix A= is created
by typing

A=[1 2 3 ; 4 5 6; 7 8 9],

i.e., rows are separated with semi-colons. If we want to use a specific element in a vector or a matrix,
study the following example:

Example:

x=[10 20 30]

A=[ 1 2 3 ; 4 5 6 ; 7 8 9]

x(2)

A(3,1)

Here we extracted the second element of the vector by typing the variable and the position within
parantheses. The same principle holds for matrices; the first number specifies the row of the matrix,

Dept. of ECE, JSSATE, Bengaluru-60 Page 104


Digital Signal Processing Lab (15ECL57) V Semester

and the second number specifies the column of the matrix. Note that in MATLAB the first index of a
vector or matrix starts at 1, not 0 as is common with other programming languages.

If the matrices (or vectors which are special cases of a matrices) are of the same dimensions then
matrix addition, matrix subtraction and scalar multiplication works just like we are used to.

Example: Type

x=[1 2 3]

y =[4 5 6]

a=2

x+y

x-y

a*x

and observe what happens.

If want to apply an operation such as squaring each element in a matrix we have to use a dot . before
the operation we wish to apply. Type the following commands in MATLAB.

x=1:10

x.^2

A=[1 2 3 ; 4 5 6 ; 7 8 9 ]

A.^2

A^2

and observe the result. The dot allows us to do operations element wise. All built-in functions such
as sin, cos, exp and so on automatically act element wise on a matrix. Type

y=[0 1/4 1/2 3/4 1]

y=pi*y

sin(y)

and observe the result.

Dept. of ECE, JSSATE, Bengaluru-60 Page 105


Digital Signal Processing Lab (15ECL57) V Semester

How to plot with MATLAB

There are different ways of plotting in MATLAB. The following two techniques, illustrated by
examples, are probably the most useful ones.

Example 1: Plot sin(x2) on the interval [-5,5]. To do this, type the following:

x=-5:0.01:5;

y=sin(x.^2);

plot(x,y)

and observe what happens.

Example 2: Plot exp(sin(x)) on the interval [-,]. To do this, type the following:

x=linspace(-pi,pi,101);

y=exp(sin(x));

plot(x,y)

and observe what happens. The command linspace creates a vector of 101 equally spaced values
between - and  (inclusive).

Occasionally, we need to plot values that vary quite differently in magnitude. In this case, the regular
plot command fails to give us an adequate graphical picture of our data. Instead, we need a command
that plots values on a log scale. MATLAB has 3 such commands: loglog, semilogx, and semilogy. Use
the help command to see a description of each function. As an example of where we may want to use
one of these plotting routines, consider the following problem:

Example 3: Plot x5/2 for x = 10-5 to 105. To do this, type the following:

x=logspace(-5,5,101);

y=x.^(5/2);

plot(x,y)

and observe what happens. Now type the following command:

loglog(x,y)

The command logspace is similar to linspace, however it creates a vector of 101 points lograthmically
equally distributed between 10-5 and 105.

The following commands are useful when plotting:

Dept. of ECE, JSSATE, Bengaluru-60 Page 106


Digital Signal Processing Lab (15ECL57) V Semester

Graphing functions MATLAB command

Label the horizontal axis. xlabel('text')

Label the vertical axis. ylabel('text')

Attach a title to the plot. title('text')

Change the limits on the x and y axis. axis([xmin xmax ymin ymax])

"Keep plotting in the same window." hold on

Turn off the "keep-plotting-in-the-same-window-command". hold off

Dept. of ECE, JSSATE, Bengaluru-60 Page 107

You might also like