Sei sulla pagina 1di 113

Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 1
Title: Starting with MATLAB.

Equipment Required: Personal computer (PC) with windows operating system


and MATLAB software

Theory:-
MATLAB is a powerful computing system for handling the calculations involved in
scientific and engineering problems. The name MATLAB stands for MATrix LABoratory,
because the system was designed to make matrix computations particularly easy.
One of the many things about MATLAB (and which distinguishes it from many
other computer programming systems, such as C++ and Java) is that you can use it
interactively. This means you type some commands at the special MATLAB prompt, and
get the answers immediately. The problems solved in this way can be very simple, like
finding a square root, or they can be much more complicated, like finding the solution to
a system of differential equations. For many technical problems you have to enter only
one or two commands, and you get the answers at once.

MATLAB WINDOWS:-
Window Purpose
Command Window Main window, enters variables, runs programs.
Figure Window Contains output from graphic commands.
Editor Window Creates and debugs script and function files.
Help Window Provides help information.
Launch Pad Window Provides access to tools, demos, and documentation.
Command History Window Logs commands entered in the Command Window
Workspace Window Provides information about the variables that are used.
Current Directory Window Shows the files in the current directory
1
Page
Digital Signal Processing Lab Manual

Workspace Window

Command Window

Command
History Window

Procedure:-
1) To start MATLAB from Windows, double-click the MATLAB icon on your Windows
desktop. When MATLAB starts, the MATLAB desktop opens as shown in Figure
1.1. The window in the desktop that concerns us for this experiment is the
Command Window, where the special >> prompt appears. This prompt means
that MATLAB is waiting for a command. You can quit MATLAB at any time with
one of the following:
➤ Select Exit MATLAB from the desktop File menu.
➤ Enter quit or exit at the Command Window prompt.
2) Once you have started MATLAB, try the following exercises in the Command
Window.
(a) Type 2+3 after the >> prompt, followed by Enter, i.e. press the Enter key, as
indicated by <Enter>, below:
>>2+3 <Enter>
Commands are only carried out when you press Enter. The answer in this
case is, of course, 5.
2

(b) Next try the following:


Page
Digital Signal Processing Lab Manual

>>3-2 <Enter>
>>2*3 <Enter>
>>1/2 <Enter>
>> 2ˆ3 <Enter>
>>2\1 <Enter>
symbols *, / and ˆ, are multiplication, division and exponentiation. The backslash
means the denominator is to the left of the symbol and the numerator is to the
right of the symbol; the result for the last command is 0.5. This operation is
equivalent to 1/2.
3) Assign values to variables to do arithmetical operations with the variables.
(a) Enter the command a = 2, i.e. the MATLAB command line should look
like this:
>>a = 2 <Enter>
The symbol a is called a variable. This statement assigns the value of 2 to a.
(b)Now enter the statement
>>b = 3; <Enter>
The semicolon (;) prevents the value of b from being displayed.
4) The output format is fixed-point with 4 decimal digits (called short), which is the
default format for numerical values. The format can be changed with the
formatcommand. Once the format command is entered, all the output that
follows is displayed in the specified format. Several of the available formats are
listed and described in Table below.

Display formats
Command Description Example
format short Fixed-point with 4 decimal digits for: >> format short
0.001 ≤ number ≤1000 Otherwise display >> 290/7
format short e. ans = 41.4286
format long Fixed-point with 14decimal digits. >> format long
>> 290/7
ans = 41.428571428571431
format short e Scientific notation with 4 decimal digits. >> format short e
>> 290/7
ans = 4.1429e+001
format long e Scientific notation with 15 decimal digits. >> format long e
>> 290/7
ans =
4.142857142857143e+001
3

format short g Best of 5-digit fixed or floating point. >> format short g
Page

>> 290/7
Digital Signal Processing Lab Manual

ans = 41.429
format long g Best of I5-digit fixed or floating point. >> format long g
>> 290/7
ans = 41.4285714285714
format bank Two decimal digits. >> format bank
>> 290/7
ans = 41.43

5) ELEMENTARY MATH BUILT-IN FUNCTIONS


In addition to basic arithmetic operations, expressions in MATLAB can
include functions. MATLAB has a very large library of built-in functions. A function
has a name and an argument in parentheses. For example, the function that
calculates the square root of a number is sqrt(x). Its name is sqrt, and the
argument is x.

Elementary math functions

Function Description Example


sqrt(x) Square root. >> sqrt(81)
ans = 9.00
exp(x) Exponential (ex). >> exp(5)
ans = 148.41
abs (x) Absolute value. >> abs (-24)
ans = 24.00
log (x) Natural logarithm. >> log(1000)
Base e logarithm (In). ans = 6.91
log10(x) Base 10 logarithm. >> log10(1000)
ans = 3.00
factorial (x) The factorial function x! >> factorial (5)
(x must be a positive ans = 120.00
integer.)

Function Description Example


sin(x) Sine of angle x (x in >> sin(pi/6)
radians). ans = 0.5000
cos(x) Cosine of angle x (x in >> cos(pi/6)
4

radians). ans = 0.8660


Page
Digital Signal Processing Lab Manual

tan (x) Tangent of angle x (x in >> tan(pi/6)


radians). ans = 0.5774
cot (x) Cotangent of angle x (.x in >> cot(pi/6)
radians). ans = 1.7321

Rounding functions
Function Description Example
round (x) Round to the nearest >> round (17/5)
integer. ans = 3
fix(x) Round towards zero. >> fix (13/5)
ans = 2
ceil(x) Round towards infinity. >> ceil (11/5)
ans = 3
floor (x) Round towards minus >> floor(-9/4)
infinity. ans = -3
rem(x,y) Returns the remainder after >> rem(13,5)
x is divided by y. ans = 3
sign(x) Signum function. Returns 1 >> sign(5)
if ans = 1
x > 0 , -1 if x < 0, and 0 if x =
0

Rules About VariableNames


Variablenames:
 Can be up to 63 characters long
 Can contain letters, digits, and the underscore character
 Must begin With a letter.
 MATLAB is case sensitive; it distinguishes between uppercase and lowercase
letters. For example, AA,Aa, aA, and aa are the names of four different variables.
 Avoid using the names of a built-in function for a variable (i.e. avoid using: cos,
sin, exp, sqrt, etc.). Once a function name is used to define a variable, the
function cannot be used.
Problems:-
Solve the following problems in the Command Window.
1) Calculate:
35.7 * 64  7 3
5

a)
45  5 2
Page
Digital Signal Processing Lab Manual

37
b) 5 * 7 * 6 2 
4 (93  652)
2732 / 3 552
c) (2  7) 3  
2 3
2733
d) 23  7 3   553 / 2
2
e) 37 log(76) 3
 910
7 3  546
4
 23
f) 43* 250
( 453 ) 3
e
 
tan ln 8 
5 7
2

g) cos2   sin    6 
 6   8  7
  ln 8 
tan 
 5  2  7 
2

h) cos  sin     6 
 6   8  7*
5
2
2) Define the variable x as x = 13.5, then evaluate:
a) x 3  5 x 2  26.7 x  52
14 x 3
b)
e3x
c) log x 2  x 3
3) Define the variable x and z as x = 9.6, and z=8.1, then evaluate
3
 2z  5
a) xz   2

 3x 
 xz
b) 4433z  e
2x ( x  z)
4) Define the variable a, b, c, and d as:
a = 15.62, b =-7.08, c = 62.5 and d = 0.5(ab-c)
evaluate:
ab (a  d ) 2
a) a  *
c ab
ad  cd
20 30
d
 

6

b) de 
2 a b
abcd
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 2
Title: Arrays.

Equipment Required: Personal computer (PC) with windows operating system


and MATLAB software

Theory:-
Arrays: vectors and matrices:-
As mentioned earlier, the name MATLAB stands for MATrix LABoratory because
MATLAB has been designed to work with matrices. A matrix is a rectangular object (e.g.
a table) consisting of rows and columns. A vector is a special type of matrix, having only
one row, or one column.
MATLAB handles vectors and matrices in the same way, but since vectors are easier to
think about than matrices.

Procedure:-
1) One-Dimensional array:-
A one dimensional array is a list of number that is placed in a row or a column.
The vector is created by typing the elements inside the square brackets [ ]
Variable_name = [ type vector elements]
1.1)Row vector:-
To create a row vector type the elements with a space or a comma
between the elements inside the square brackets
>> yr = [1999 2000 2001 2003 2004]
yr =
1999 2000 2001 2003 2004

>> yr = [1999, 2000, 2001, 2003, 2004]


yr =
1999 2000 2001 2003 2004
1.2)Column vector :-
To create column vector type the left square brackets [and then enter the
elements with a semicolon between then, or press the enter key after each element.
7

Type the right square bracket]


Page
Digital Signal Processing Lab Manual

>>Pop = [127; 130; 136; 145; 158; 178 ]


Pop =
127
130
136
145
158
178
Assignment 1:-
Create a row vector that has the elements: 32, 4, 81, 63, cos(pi/3) and 14.12
Assignment 2:-
Create a column vector that has the elements: 55, 14, ln(51), 987, 0 and 5
sin(2.5pi)

2) Creating a vector with constant spacing by specifying the first term, the spacing,
and the last term

Variable_name = [firstterm : spacing : lastterm]

Example:-

>> x = [1:2:13] First element 1, spacing 2, last element 13


x=
1 3 5 7 9 11 13

>>y = [-3:7] First element -3, last term 7. If space is omitted, the default
is 1

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

Assignment 3 : Create a row vector in which the first element is 1, the last element is
33, with an increment of 2 between the elements (1,3,5,…….,33)
Assignment 4: Create a row vector in which the first element is 15, the elements
decrease with increments of -5 and the last elements is -25
8
Page
Digital Signal Processing Lab Manual

3) Creating a vector with constant spacing by specifying the first and last terms
and the number of terms:
A vector in which the first element is xi, the last element is xf, and the number of
elements is n is created by typing the linspace command:
variable_name =linspace (xi, xi, n)
Example:-
>> va = linspace(0,8,6) 6 elements, first element 0, last element8
va =
0 1.6000 3.2000 4.8000 6.4000 8.0000
>> va = linspace(30,10,11) 11 elements, first element 30, last element10
va =
30 28 26 24 22 20 18 16 14 12 10

4) Creating a two-dimensional array (matrix)


A matrix is created by assigning the elements of the matrix to a variable. This is
done by typing the elements, row by row, inside square brackets [ ]. First type the
left bracket [ , then type the first row separating the elements with spaces or
commas. To type the next row type a semicolon or press Enter. Type the right
bracket] at the end of the last row.
variable_name = [ 1st row elements; 2nd row elements; 3rd row elements; ………;
last row elements]
Example:-
>> a = [5 35 43; 4 76 81; 21 32 40]
a=
5 35 43
4 76 81 A semicolon is typed before a
21 32 40 new line is entered.
>> a = [5 35 43
4 76 81
21 32 40] A Enter key is pressed before a
a= new line is entered.
5 35 43
4 76 81
21 32 40
Rows of a matrix can also be entered as vectors using the notation for creating vectors
with constant spacing, or the linspace command.
9
Page

Example:
Digital Signal Processing Lab Manual

>> A = [1:2:11; 0:5:25; linspace(10,60,6); 67 2 43 68 4 13]


A=
1 3 5 7 9 11
0 5 10 15 20 25
10 20 30 40 50 60
67 2 43 68 4 13
In this example the first two rows were entered as vectors using the notation of
constant spacing, the third row was entered using the linspacecommand, and in the last
row the elements were entered individually.
5) The zeros, ones and eye Commands
The zeros (m, n), the ones(m, n), and eye (n) commands can be used to create
matrices that have elements with special values. The zeros (m, n) and the ones (m, n)
commands create a matrix with m rows and n columns, in which all the elements are the
numbers 0 and 1, respectively. The eye (n) command creates a square matrix with n
rows and n columns in which the diagonal elements are equal to 1, and the rest of the
elements are 0.This matrix is called the identity matrix.
Examples:
>> zr = zeros(3,4)
zr =
0 0 0 0
0 0 0 0
0 0 0 0
>> ne=ones(3,5)
ne =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
>> idn = eye(5)
idn =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

6) The Transpose Operator:-


The transpose operator is applied by typing a single quote' following the variable to
be transposed.
10
Page

Examples:
Digital Signal Processing Lab Manual

>> aa = [3 8 1]
aa =
3 8 1
>> bb = aa'
bb =
3
8
1
>> C = [2 55 14 8 ; 21 5 32 11; 1 2 3 4]
C=
2 55 14 8
21 5 32 11
1 2 3 4
>> D = C'
D=
2 21 1
55 5 2
14 32 3
8 11 4
7) Array Addressing
Elements in an array (either vector or matrix) can be addressed individually or in
subgroups.
7.1) Vector:-
The address of an element in a vector is its position in the row (or column). For a
vector named ve, ve (k) refers to the element in position k. The first position is 1. For
example, if the vector ve has nine elements:
ve=35 46 78 2351481355
then
ve(4) = 23, ve(7) = 81, and ve(1) = 35.
Example:-
>> VCT = [35 46 78 23 5 14 81 3 55] Define a Vector
VCT =
35 46 78 23 5 14 81 3 55
>> VCT(4) Display the fourth element
ans =
23
>> VCT(6)=273 Assign a new value to the sixth element
VCT =
11

35 46 78 23 5 273 81 3 55 The whole vector is displayed


Page

>> VCT(2)+VCT(8)
Digital Signal Processing Lab Manual

ans =
49 Use the vector elements in
>> VCT(5)^VCT(8)+sqrt(VCT(7)) mathematical expressions
ans =
134
7.2) Matrix:-
The address of an element in a matrix is its position, defined by the row
number and the column number where it is located. For a matrix assigned to a
variable ma, ma(k,p)refers to the element in row k and column p.
For example, if the matrix is:
 3 11 6 5
ma   4 7 10 2
 
13 9 0 8
then, ma(1,1) = 3, and ma(2,3) = 10.
As with vectors, it is possible to change the value of just one element of a
matrix by assigning a new value to that element. Also, single elements can be
used
Like variables in mathematical expressions and functions.
Examples:
>> MAT = [3 11 6 5; 4 7 10 2; 13 9 0 8]
MAT = Create a 3 X 4 matrix
3 11 6 5
4 7 10 2
13 9 0 8
>> MAT(3,1)
ans =
13
>> MAT = [3 11 6 5; 4 7 10 2; 13 9 0 8]
MAT =
3 11 6 5
4 7 10 2
13 9 0 8
>> MAT(3,1)=20 Assign a new value to the (3,1) element.
MAT =
3 11 6 5
4 7 10 2
20 9 0 8
12

>> MAT(2,4)-MAT(1,2) Use the elements in a mathematical expression


ans =
Page

-9
Digital Signal Processing Lab Manual

7.3) Using A Colon: In Addressing Arrays


A colon can be used to address a range of elements in a vector or a matrix.
For a vector:
va(:) Refers to all the elements of the vector va (either a row or a column vector).
va(m:n) Refers to elements m through n of the vector va.
Example:

>> v = [4 15 8 12 34 2 50 23 11] A vector v is created


v=
4 15 8 12 34 2 50 23 11
>> u = v(3:7)
A vector u is created from
u=
the elements 3 through 7
8 12 34 2 50 of vector v.

For a matrix:
A( :,n) Refers to the elements in all the rows of column n of the matrix A.
A(n,:) Refers to the elements in all the columns of row n of the matrix A.
A(:,m:n) Refers to the elements in all the rows between columns m and n of the
matrix A.
A(m:n,:) Refers to the elements in all the columns between rows m and n of the
matrix A.
A(m:1},p:q) Refers to the elements in rows m through n and columns p through q
of the matrix A.
Example:-
>> A = [1 3 5 7 9 11; 2 4 6 8 10 12; 3 6 9 12 15 18]
A=
1 3 5 7 9 11
2 4 6 8 10 12 Define a matrix A with 3
3 6 9 12 15 18 rows and 6 columns.
>> B = A(:,3)
B= Define a column vector B from the
5 elements in all the rows of column 3
6 in matrix A.
9
>> C = A(2,:)
Define a row vector C from the elements in
C=
all the columns of row 2 in matrix A.
2 4 6 8 10 12
>> E = A(1:3,:)
13

E= Define a column matrix E from the


elements in the rows 1 through 3 and
Page

1 3 5 7 9 11
all the columns in matrix A.
Digital Signal Processing Lab Manual

2 4 6 8 10 12
3 6 9 12 15 18
>> F = A(1:3,2:4)
F= Define a column matrix F from the elements in
3 5 7 the rows 1 through 3 and the columns 2
4 6 8 through 4 in matrix A.
6 9 12
It is possible, to select only specific elements, or specific rows and columns
of existing variables to create new variables. This is done by typing the selected
elements or rows or columns inside brackets, as shown below:
>> v = 4:3:34 Create a vector v with 11 elements.
v=
4 7 10 13 16 19 22 25 28 31 34
>> u = v([3,5,7:10])
Create a vector u from the 3rd, the 5th , and
u= 7th through 10th elements of v
10 16 22 25 28 31
>> A = [10:-1:4;ones(1,7);2:2:14;zeros(1,7)]
A=
10 9 8 7 6 5 4 Create a 4 X 7 matrix A.
1 1 1 1 1 1 1
2 4 6 8 10 12 14
0 0 0 0 0 0 0
>> B = A([1,3],[1,3,5:7]) Create a matrix B from the 1st and
B= 3rd rows and 1st,3rd , and 5th through
10 8 6 5 4 7th columns of A.
2 6 10 12 14
8) Adding Elements to Existing Variables
A variable that exists as a vector, or a matrix, can be changed by adding elements
to it.
8.1) Adding elements to a vector:
Elements can be added to an existing vector by assigning values to the
new elements
Example:- Define vector DF with 4 elements
>> DF = 1:4
DF =
1 2 3 4
>> DF(5:10)=10:5:35 Adding 6 elements starting with the 5th.
DF =
14

1 2 3 4 10 15 20 25 30 35
Page

>> AD = [5 7 2] Define vector AD with 3 elements


Digital Signal Processing Lab Manual

AD =
5 7 2
Assign a value to the 8th element.
>> AD(8)=4
AD =
5 7 2 0 0 0 0 4 MATLAB assignd zeros to the 4th
>> AR(5)=24 through 7th elements,
AR =
0 0 0 0 24
8.2) Adding elements to a matrix:
Rows and/or columns can be added, to an existing matrix by assigning values to
the new rows or columns. This can be done by assigning new values, or by appending
existing variables. This must be done carefully since the size of the added rows or
columns must fit the existing matrix.
Examples:
>> E = [1 2 3 4; 5 6 7 8] Define a 2X4 matrix E.
E=
1 2 3 4
5 6 7 8
>> E(3,:)=[10:4:22] Adding the vector 10 14 18 22 as
E= the third row of E.
1 2 3 4
5 6 7 8
10 14 18 22
>> K = eye(3) Define a 3X3 matrix K.
K=
1 0 0
0 1 0
0 0 1
>> G = [E K] Append the matrix K to matrix E. the
G= number of rows in E and K must be the
1 2 3 4 1 0 0 same.
5 6 7 8 0 1 0
10 14 18 22 0 0 1
9) Built-in Functions for Handling Arrays:-
MATLAB has many built-in functions for managing and handling arrays. Some of
these are listed below:
15
Page

Built-in functions for handling arrays


Digital Signal Processing Lab Manual

Function Description Example


length (A) Returns the number of elements in >> A = [5 9 2 4];
the vector A. >> length(A)
ans =
4
size(A) Returns a row vector [m, n] , >> A = [6 1 4 0 12; 5 19 6 8 2];
where m and n are the size m X n >> size(A)
of the array A. ans =
2 5
reshape(A,m,n) Rearrange a matrix A that has r >> A = [5 1 6; 8 0 2]
rows and s columns to have m A=
rows and n columns. r times s 5 1 6
must be equal to m times n. 8 0 2
>> B = reshape(A,3,2)
B=
5 0
8 6
1 2
diag(v) When v is a vector, creates a >> v = [7 4 2]
square matrix with the elements of v =
v in the diagonal. 7 4 2
>> A = diag(v)
A=
7 0 0
0 4 0
0 0 2
diag(A) When A is a matrix, creates a >> A = [1 2 3; 4 5 6; 7 8 9]
vector from the diagonal elements A =
of A. 1 2 3
4 5 6
7 8 9
>> vec = diag(A)
vec =
1
5
9
16
Page

Assignment 5:-
Digital Signal Processing Lab Manual

Create a row vector with 15 equally spaced elements in which the first element is
7 and the last element is 40.
Assignment 6:-
Create a column vector with 12 equally spaced elements in which the first
element is -1 and the last element is -15.
Assignment 7:-
Create the matrix shown below by using the vector notation for creating vectors
with constant spacing and/or the linspace command when entering the rows.

1 4 7 10 13 16 19 22 25 
B  72 66 60 54 48 42 36 30 24 
 
 0 0.125 0.250 0.375 0.500 0.625 0.750 0.875 1.000
Assignment 8:-

Create the following matrix A:


 6 43 2 11 87
A   12 6 34 0 5 
 
 34 18 7 41 9 
Use the matrix A to:
a) Create a five-element row vector named va that contains the elements of the
second row of A.
b) Create a three-element row vector named vb that contains the elements of the
fourth column ofA.
c) Create a ten-element row vector named vc that contains the elements of the
first and second rows of A.
d) Create a six-element row vector named vd that contains the elements of the
second and fifth columns of A.
Assignment 9:-
Create the following matrix c:
2 4 6 8 10 
A  3 6 9 12 15 
 
7 14 21 28 35
Use the matrix C to:
17

a) Create a three-element column vector named ua that contains the elements of


Page

the third column of C.


Digital Signal Processing Lab Manual

b) Create a five-element column vector named ub that contains the elements of


the second row of c:
c) Create a nine-element column vector named uc that contains the elements of
the first, third and fifth columns of C.
d) Create a ten-element column vector named ud that contains the elements of
the first and second rows of C.
Assignment 10:-
Create the following matrix A:

I 2 3 4 5 6 7
 2 4 6 8 10 12 14 
A 
211815 12 9 6 3 
 5 1015 20 25 30 35
 
a) Create a 3 x 4 matrix B from the 1st, 3rd, and 4th rows, and the 1st, 3rd through
5th, and 7th columns of the matrixA.
b) Create a 15 elements-long row vector u from the elements of the third row,
and the 5th and 7th columns of the matrixA.

18
Page
Digital Signal Processing Lab Manual

Faculty of Engineering
Experiment # 3
Title: Two Dimensional Plots.

Equipment Required: Personal computer (PC) with windows operating system


and MATLAB software
Theory:-
1) The plot Command:-

The plot command is used to create two-dimensional plots. The simplest form of
the command is:
plot(x,y)

Vector Vector

The arguments x and y are each are vector (one-dimensional array). Both vectors must
have the same number of elements.
The plot command has additional optional arguments that can be used to specify
the color and style of the line and the color and type of markers, if any are desired. With
these options the command has the form:

Plot(x,y,’ line specifiers ' ,'PropertyName' ,PropertyValue)

(Optional) Properties with


Vector Vector (Optional) Specifiers
that define the type values that can be used to
and color of the line specify the line width, and
and markers. marker's size and edge, and
fill colors.
1.1) Line Specifiers:-
The line style specifiers are:
Line Style Specifier
solid (default) -
Dashed --
Dotted :
dash-dot -.
19

 The line color specifiers are:


Page
Digital Signal Processing Lab Manual

Line Color Specifier Line Color Specifier


red r magenta m
green g yellow y
blue b black k
cyan c white w
 The marker type specifiers are:
Marker Type Specifier Marker Type Specifier
plus sign + square s
circle o diamond d
asterisk * five-pointed star p
point . six-pointed star h
Notes about using the specifiers:
 The specifiers are typed inside the plotcommand as strings.
 Within the string the specifiers can be typed in any order.
 The specifiers are optional. This means that none, one, two, or all the three can
be included in a command.
LEGEND
PLOT TITLE light Intensity as a Function of Distance
1200

Theory
Experiment
1000

800
INTENSITY (lux)

Comparison between theory and experiment

Y AXIS LABEL 600 TEXT


LABEL

400
MARKER

200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
20

X AXIS LABEL
2) THE fplot COMMAND
Page
Digital Signal Processing Lab Manual

The fplot command plots a function with the form y = f(x) between specified limits. The
command has the form:

fplot('function' ,limits,line specifiers)

The function The domain of x, Specifiers that define


to be plotted. and optionally, the type and color of
the limits of the y the line and markers
axis. (optional).

2.1) function: The function can be typed directly as a string inside the command. For
example, if the function that is being plotted is f(x) = 8x2+ 5cos(x), it is (optional).
and markers typed as:
'8*x^2+5*cos(x) '.

2.2) limits: The limits is a vector with two elements that specify the domain of x [xmin,
xmax], or a vector with four elements that specifies the domain of x and the limits of the
y-axis [xmin, xmax, ymin, ymax].

3) Plotting Multiple Graphs in the Same Plot:-

In many situations there is a need to make several graphs in the same plot. There are
three methods to plot multiple graphs in one figure.
 By using the plot command
 By using the hold on, hold off commands
 By using the line command.
3.1) Using plot command:-
Two or more graphs can be created in the same plot by typing pairs of vectors
inside the plot command. The command:
plot(x,y,u,v,t,h)
creates three graphs: y vs. x, v vs. u, and h vs. t, all in the same plot. The vectors
of each pair must be of the same length. MATLAB automatically plots the graphs in
different colors so that they can be identified. It is also possible to add line specifiers
following each pair. For example the command:
plot(x,y,'-b',u,v,'--r',t,h,'g:' )

plots y vs. x with a solid blue line, v vs u with a dashed red line, and h vs. t with a
21

dotted green line.


Page
Digital Signal Processing Lab Manual

3.2) Using the hold on, hold off Commands:-

To plot several graphs using the hold on, hold off commands, one graph is plotted
first with the plot command. Then the hold on command is typed. This keeps the Figure
Window with the first plot open, including the axis properties and formatting if any was
done. Additional graphs can be added with plot commands that are typed next. Each
plot command creates a graph that is added to that figure. The hold off command stops
this process. It returns MATLAB to the default mode in which the plot command erases
the previous plot and resets the axis properties.

3.3) Using the line Command

With the line command additional graphs (lines) can be added to a plot that already
exists. The form of the line command is:

line(x,y, 'PropertyName' ,PropertyValue)

(Optional) Properties with values that can be


used to specify the line style, color, and width,
marker type, size, and edge and fill colors.

The format of the linecommand is almost the same as the plot command

4) Formatting a Plot Using Commands

The formatting commands are entered after the plot or the fplot commands. The
various formatting commands are:

4.1) The xlabel and ylabel commands:-

Labels can be placed next to the axes with the xlabel and ylabel commands which
have the form:

xlabel('text as string')

ylabel ('text as string')

4.2) The title command:-


A title can be added to the plot with the command:
22

title ('text as string')


Page

The text is placed at the top of the figure as a title.


Digital Signal Processing Lab Manual

4.3) The text command:-


A text label can be placed in the plot with the text or gtext commands:

text(x,y, 'text as string')


gtext('text as string')

The text command places the text in the figure such that the first character is
Positioned at the point with the coordinates x, y (according to the axes of the figure).
The gtext command places the text at a position specified by the user. When
the command is executed, the Figure Window opens and the user specifies the Position
with the mouse.
4.4) legend command:-
The legend command places a legend on the plot. The legend shows a sample of
the line type of each graph that is plotted, and places a label, specified by the
user,beside the line sample. The form of the command is:
legend('string1', 'string1', ………….. ,pos )
The strings are the labels that are placed next to the line sample

4.5) The axis command:-


When the plot (x, y) command is executed, MATLAB creates axes with limits that
are based on the minimum and maximum values of the elements of x and y. The axis
command can be used to change the range and the appearance of the axes. In many
situations a graph looks better if the range of the axes extend beyond the range of the
data. The following are some of the possible forms of the axis command:

axis( [xmin, xmax] ) Sets the Iimits of the x axis (xmin and xmax are numbers).

axis([xmin,xmax,ymin,ymax]) Sets the limits of both the x and y axes.

5) Plotting multiple plots on the same page:-


Multiple plots on the same page can be created with the subplot command.
subplot(m,n,p)
The command divides the Figure Window (page when printed) into m x n
rectangular subplots where plots will be created. The subplots are arranged like
elements in a m X n matrix where each element is a subplot. The subplots are numbered
from 1 through m. n. The upper left is 1 and the lower right is the number m x n. The
23

numbers increase from left to right within a row, from the first row to the last. The
Page

command subplot(m, n, p) makes the subplot P current.


Digital Signal Processing Lab Manual

Procedure:-
Execute following example on MATLAB Command Window.

1. The plot Command:-


>> x = [1 2 3 5 7 7.5 8 10]
>> y = [2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)

The following table contains sales data of a company from 1988 to 1994.

YEAR 1988 1989 1990 1991 1992 1993 1994


SALES 8 12 20 22 18 24 27
(millions)

To plot this data, the list of years is assigned to one vector (named yr), and the
corresponding sale data is assigned to a second vector (named sle). The Command
Window where the vectors are created and the plot command is used is shown below:

>> yr = [1988:1:1994]
>> sle=[8 12 20 22 18 24 27]
>> plot(yr,sle,'--r*','linewidth',2,'markersize',12)

Line Specifiers: Property Name and Property Value:


dashed red line and the line width is 2 points and the
asterisk marker. markers size is 12 point.

2. THE fplot COMMAND:-

A plot of the function y = x2+ 4sin(2x) - 1 for -3 ≤ x ≤ 3 can be created with the fplot
command by typing:

>> fplot('x^2+4*sin(2*x)-1',[-3 3])

The plot of this function can be created with plot command as follows:

x = [-3:.1: 3]; Create vector x with the domain of the function.


24

y = x.^2+4.*sin(2.*x)-1;
Create vector y with the function value at each x.
Page

plot(x,y)
Plot y as a function of x.
Digital Signal Processing Lab Manual

3. Plotting Multiple Graphs in the Same Plot:-


Plot the function y = 3x3- 26x+ 10, and its first and second derivatives, for –2 ≤x≤4, all
in the same plot.
Solution
The first derivative of the function is: y' = 9x2- 26.
The second derivative of the function is: y" = 18x.
3.1 Using the plot command:-
A script file that creates a vector x, and calculates the values of y, y' , and y" is:
x =[-2:0.01:4]; Create vector x with the domain of the function.

y =3*x.^3 -26*x+ 6; Create vector y with the function value at each x.

yd = 9*x.^2-26; Create vector yd with values of the first derivative.

ydd =18*x; Create vector ydd with values of the second derivative.
plot(x,y,'-b',x,yd,'--r',x,ydd,':k')
Create three graphs, y vs. x, yd vs x and
ydd vs. x in the same figure.

3.2 Using the hold on, hold off Commands:-


x =[-2:0.01:4];
y =3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd =18*x;
plot(x,y,'-b') The first graph is created.
hold on
plot(x,yd,'--r') Two more graphs are added to the figure
plot(x,ydd,':k')
hold off
xd = [10:2:22];
yd = [950 640 460 340 250 180 140];
4. Formatting a Plot Using Commands
x = [10:0.1 :22];
y = 95000./x.^2;
25

xd =[10:2:22];
Page

yd =[950 640 460 340 250 180 140];


Digital Signal Processing Lab Manual

plot(x,y,'-','LineWidth', 1.0)
xlabel('DISTANCE (cm)')
ylabel('INTENSITY (lux)')
title('light Intensity as a Function of Distance')
axis([8 24 0 1200])
text(14,700,'Comparison between theory and experiment')
hold on
plot(xd,yd,'ro-- ','LineWidth',1.0,'markersize',10)
legend('Theory','Experiment',0);
hold off

Problems:-
Solve the following problems in MATLAB Command Window.

1) Make two separate plots of the function f ( x)  0.6 x  5 x  9 x  2


5 3

one plot for -4≤x≤4, and one for -2.7≤x≤2.7.

x  x  1 for -10 ≤ x ≤ 10
2

2) Plot the function f ( x) 


x  x 1
2

3) Use the fplot command to plot the


function: f ( x)  0.01x  0.03x  0.4 x  2 x  6 x  5
5 4 3 2

In the domain -4 ≤ x ≤ 6
4) Plot the following data in MATLAB
Year 1990 1991 1992 1993 1994 1995 1996
Minimum Temperature 10C 11C 9C 12C 8C 11C 6C
Maximum Temperature 45C 49C 46C 50C 48C 44C 47C
a) Label x Axis as year and y axis as temperature
b) The color of the Minimum temp graph should be blue and maximum temp
graph should be red.
26

c) The range of x Axis should be between 1990 to 1996 and y axis 4 to 50


d) The title of the graph should be “seven years temperature record”.
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 4
Title: Functions and Function Files.
Equipment Required: Personal computer (PC) with windows operating system
and MATLAB software
Theory:-
Many functions are programmed inside MATLAB as built-in functions, and can be
used in mathematical expressions simply by typing their name with an argument
examples are sin (x), cos (x), sqrt(x), and exp (x). Frequently, in computer programs,
there is a need to calculate the value of functions that are not built-in. When a function
expression is simple and needs to be calculated only once, it can be typed as part of the
program. However, when a function needs to be evaluated many times for different
values of arguments it is convenient to create a ''user defined" function. Once the new
function is created (saved) it can be used just like the built-in functions.
1) Creating a Function File:-
Function files are created and edited, like script files, in the Editor/Debugger
Window. This window is opened from the Command Window. In the File menu, select
New, and then select M-fIle.
2) Structure of a Function File:-
The structure of a typical function file is shown in Figure below.

27
Page
Digital Signal Processing Lab Manual

Function definition line

The H1 line

Help text

Function body
(Computer program).

Assignment values to output arguments.

2.1) Function Definition Line:-

The first executable line in a function file must be the function definition line.
Otherwise the file is considered a script file. The function definition line:

 Defines the file as a function file


 Defines the name of the function.
 Defines the number and order of the input and output arguments.

function [output arguments] = function_name (input arguments)

The word function must be A list of output The name A list of input
the first word, and must arguments typed of the arguments typed
be typed in lower-case inside brackets. function. inside parentheses.
letters.

Input and Output Arguments:-

The input and output arguments are used to transfer data into and out of the
function. The input arguments are listed inside parentheses following the function
name. Usually, there is at least one input argument, although it is possible to have a
function that has no input arguments. If there are more than one, the input arguments
28

are separated with commas. The following are example of function definition lines with
Page

different combinations of input and output arguments.


Digital Signal Processing Lab Manual

Function definition line Comments

function[mpay,tpay]= loan(amount,rate,years) Three input arguments, two output arguments.

function [A] =RectArea(a,b) Two input arguments, one output argument.

function A = RectArea( a, b) Same as above, one output argument can be


typed without the brackets.

2.2) The H1 Line and Help Text Lines:-

The H1 line and help text lines are comment lines (lines that begin with the
percent% sign) following the function definition line. They are optional, but frequently
used to provide information about the function. The comment lines that are typed
between the function definition line and the first non-comment line are displayed when
the user types help function_name in the Command Window.

2.3) Function Body:-

The function body contains the computer program (code) that actually performs the
computations. The code can use all MATLAB programming features. This includes
calculations, assignments, any built-in or user-defined functions, flow control,
comments, blank lines, and interactive input and output.

3) Inline Functions

Function files can be used for simple mathematical functions, for large and
complicated math functions that require extensive programming, and as subprograms in
large computer programs. In cases when the value of a relatively simple mathematical
function has to be determined many times within a program, MATLAB provides the
option of using inline functions. An inline function is defined within the computer code
(not as a separate file like a function file) and is then used in the code. Inline functions
can be defined in any part of MATLAB.

Inline functions are created with the inline command according to the following format:

name = inline('math expression typed as a string')


29
Page
Digital Signal Processing Lab Manual

Procedure:-
Execute the following example in MATLAB

1) The function:-

Example:-

Write a function file for the function 4


x 3x  5 the input to the function is x
f ( x) 
( x  1)
2 2

and the output is f(x). Write the function such that x can be a vector. Use the function to
calculate:

a) f(x) for x =6.


b) f(x) for x = 1,3,5,7,9, and 11.

Open the Editor/Debugger Window. This window is opened from the Command
Window. In the File menu, select New, and then select M-fIle. Once the Editor/Debugger
Window opens write the following function in it

function [y] = exp4one(x) Function definition line


y= (x.^4.*sqrt(3*x+5))./(x.^2+1).^2; Assignment to output argument.

a) Calculating the function for x = 6 can be done by typing exp4one(6) in the


Command window
>> exp4one(6)
ans =
4.5401
To calculate the function for several values of x, a vector with the values of x is first
created, and then used for the argument of the function.
>> x = 1:2:11
x=
1 3 5 7 9 11
>> exp4one(x)
ans =
0.7071 3.0307 4.1347 4.8971 5.5197 6.0638
30
Page
Digital Signal Processing Lab Manual

The inline Function:-


x2
The function e can be defined (in the Command Window) as an inline
f ( x) 
x 5
2

function for x as a scalar by:

>> FA = inline('exp(x^2)/sqrt(x^2+5)')
FA =
Inline function:
FA(x) = exp(x^2)/sqrt(x^2+5)

Then the value of f(x) at different value of x can be calculated as


>> FA(2)
ans =
18.1994
>> FA(3)
ans =
2.1656e+003

If there are two variables then the f(x, y) = 2x2- 4xy+y2 can be defined as an inline
function by:
>> HA = inline('2*x^2-4*x*y+y^2')
HA =
Inline function:
HA(x,y) = 2*x^2-4*x*y+y^2

MATLAB arranges the arguments in alphabetical order. The function can be used for
different values of x and y. For example,
HA(2,3)gives:

>> HA(2,3)
ans =
-7 31
Page
Digital Signal Processing Lab Manual

Assignment :- Converting temperature units


Write a user-defined function (name it FtoC) that converts temperature in degrees F to
temperature in degrees C. Use the function to convert
a) 32 degrees F to degrees C.
b) 32, 35,40,60,80 degrees F to degrees C.

32
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 5
Title: Elementary Sequence.

Equipment Required: Personal computer (PC) with windows operating system


and MATLAB software

Introduction:-
A discrete time signal is represented as a sequence of numbers, called samples. These
samples are denoted by x(n) where the variable n is integer valued and represents in
discrete instances in time. An example of a discrete time signal is:

x(n) = {2 ,1 ,-1 ,0 ,1 ,4 ,3 ,7} …(1)

where the up arrow indicates the sample at n = 0

In MATLAB, a finite duration sequence is represented by a row vector. However, such a


vector does not have any information about sample position n. Therefore a correct
representation of x(n) would require two vectors, one each for x and n ,
To represent the sequence defined in eq1, the following MATLAB command can
be used:

>> n = [-3,-2,-1,0,1,2,3,4] x=[2,1,-1,0,1,4,3,7]

We use several elementary sequences in digital signal processing for analysis purposes.
Their definitions and MATLAB representations are given below.

Procedure:-
1. Unit sample sequence:

1, n  0 ........., 0,0,1,0,0,...... 


 (n)    
33

0, n  0   
Page
Digital Signal Processing Lab Manual

In MATLAB the function zeros (1, N) generates a row vector of N zeros, which can be
used to implement δ (n) over a finite interval. However, the logical relation n==0 is an
elegant way of implementing δ (n) . For example, to implement

1, n  no
 ( n  no )  
0, n  no

over the n1  n0  n2 interval, we will use the following MATLAB function.

function [x,n] = impseq(n0,n1,n2)


% Generates x(n) = delta(n-nO); n1 <= n <= n2
% ---------------------------------------------¬
% [x,n] = impseq(n0,n1,n2)
%
n= [n1:n2];
x = [(n-n0) == 0];

MATLAB Script:-

% Generation of a Unit Sample Sequence


% Generate a vector from -10 to 20
[x,n]=impseq(1,-10,20)
%plot the unit sample sequence
stem(n,u);
xlabel(‘time index n’);ylabel(‘Amplitude’);
title(‘Unit Sample Sequence’);
axis([-10 20 0 1.2]);

Task 1:
Generate and plot the sequence

δ(n–30) -20≤n≤120
34

MATLAB CODE:-
Page
Digital Signal Processing Lab Manual

2. Unit step sequence:


1, n  0 ....., 0,0,1,1,1,....... 
u (n)    
0, n  0   
In MATLAB the function ones(1,N) generates a row vector of N ones. It can be
used to generate u( n) over a finite interval. Once again an elegant approach is to use
the logical relation n>=0. To implement
1, n  n o
u ( n  no )  
0, n  n o
over the n1  n0  n2 interval, we will use the following MATLAB function.

function [x,n] = stepseq(n0,n1,n2)


% Generates x(n)= u(n-nO); n1 <= n <= n2
%---------------------------------------------------------------
% [x,n] = stepseq(n0,n1,n2)
%
n = [n1:n2]; x = [(n-n0) >= 0];

Exmaple:- Generate and plot the sequence


u(n-5) -20≤n≤10

Scrip File:-

% Generation of a Unit Step Sequence


% Generate a vector from -20 to 10
[x,n]=stepseq(5,-20,10);
%plot the unit sample sequence
stem(n,x);
xlabel('time index n');ylabel('Amplitude');
title('Unit Step Sequence');
axis([-20 10 0 1.2]);
35
Page
Digital Signal Processing Lab Manual

Task 2:
Generate and plot the sequence
u(n+5) -20≤n≤20

MATLAB CODE:-

3. Real-valued exponential sequence:-

x(n)  a n , n; a  
In MATLAB an array operator “.^” is, required to implement a real exponential
sequence.
Example:-
Generate x(n)  0.9 0  n  10 ,
n

MATLAB script:
>>n = [0:10]; x = (0.9).^n;
>>stem(n,x);

Task 3:
Generate and plot the sequence
x( n)   10  10  n  10
n

MATLAB CODE:-
36
Page

4. Complex-valued exponential sequence:


Digital Signal Processing Lab Manual

x(n)  e (  jwo ) n
Where σ is called an attenuation and wo is the frequency in radians. A MATLAB function
exp is used to generate exponential sequences.
Example:-
Generate x(n) = exp [(2 + j3) n] , 0  n  10 ,

MATLAB script:-
n = [0:10]; x = exp((2+3j)*n);
subplot(2,1,1); .
stem(n,real(x));
xlabel('Time index n');ylabel('Amplitude');
title('Real part');
subplot(2,1,2);
stem(n,imag(x));
xlabel('Time index n');ylabel('Amplitude');
title('Imaginary part');

5. Sinusoidal sequence:

x(n)  cos(w n   ), n
o

where θ is the phase in radians. A MATLAB function cos (or sin) is used to generate
sinusoidal sequences.
Example,
Generate x(n)  cos(0.1n   / 3)  2 sin( 0.5n) 0  n  10 ,

MATLAB script:
n = [0:10]; x = 3*cos(0.1*pi*n+pi/3) + 2*sin(0.5*pi*n);
37
Page

EXAMPLE
Digital Signal Processing Lab Manual

Generate and plot each of the following sequences over the indicated interval.
a. x(n)  2 (n  2)   (n  4), 5  n  5
MATLAB script:

n = [-5 : 5];
x = 2*impseq(-2,-5,5) - impseq(4,-5,5);
subplot(2,1,1);stem(n,x); title('Sequence in example a')
xlabel ('n'); ylabel('x(n)');

The plot of the sequence is shown in Figure a

.03( n 10 )
b. x(n)  n[u (n)  u (n  10)]  10e [u (n  10)  u (n  20)] 0  n  20
MATLAB script:

n = [0:20];
x1 = n.*(stepseq(0,0,20)-stepseq(10,0,20));
x2 = 10*exp(-0.3*(n-10)).*(stepseq(10,0,20)-stepseq(20,0,20));
x = x1+x2;
subplot(2,1,2); stem(n ,x); title('Sequence in example b');
xlabel(' n '); ylabel('x (n)');
The plot of the sequence is shown in Figure b.
Sequence in example a
2

1.5

1
x(n)

0.5

-0.5

-1
-5 -4 -3 -2 -1 0 1 2 3 4 5
n

Sequence in example b
10

6
x (n)

0
0 2 4 6 8 10 12 14 16 18 20
n
38
Page
Digital Signal Processing Lab Manual

Assignments:

Generate and plot each of the following sequences over the indicated interval

1. x[n] = cos πn/3 + sin πn/3 0 ≤ n ≤ 20

2. y[n] = nx[n] 0 ≤ n ≤ 20 x[n] is given in qs.1

3. x[n] = sin πn/4 0 ≤ n ≤ 10

4. y[n] = x[n]/(πn/4) -10 ≤ n ≤ 10 x[n] is given in qs.3

5. x[n] = (sin πn/4)/(sin π/4) -20 ≤ n ≤ 20

39
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 6
Title: OPERATIONS ON SEQUENCES

Equipment Required: Personal computer (PC) with windows operating system and
MATLAB software
Objective
This experiment briefly describes the Basic sequence operations and their
MATLAB equivalents.

1- Signal addition: This is a sample-by-sample addition given, by

{x1(n)} + { x 2 (n)} = {x1(n) + x 2 (n)}

It is implemented in MATLAB by the arithmetic operator "+". However, the


lengths of x1 (n) and x2 (n) must be the same. If sequences are of unequal lengths, or if
the sample positions are different for equal-length sequences, then we cannot directly
use the operator +. We have to first augment xl (n) and x2 (n) so that they have the
same position vector n (and hence the same length). This requires careful attention to
MATLAB's indexing operations. In particular, logical operation of intersection "&",
relational operations like "<=" and "==", and the find function are required to make x1
(n) and x2 (n) of equal length. The following function, called the sigadd function,
demonstrates these operations.

MATLAB FUNCTION
function [y,n] = sigadd(x1,n1,x2,n2)
% implements y(n) = x1(n)+x2(n)
% ----------------------------¬
% [y,n] = sigadd(xl,nl,x2,n2)
% y = sum sequence over n. which includes nl and n2
% xl = first sequence over nl
% x2= second sequence over n2(n2 can be different from nl)
%
n = min(min(n1),min(n2)) :max(max(n1) ,max(n2));%duration of y(n)
y1= zeros(1,length(n)); y2 = y1; %initialization
y1(find((n>=min(n1))&(n<=max(n1))==1))=x1; %x1 with duration of y
40

y2(find((n>=min(n2))&(n<=max(n2))==1))=x2; %x2 with duration of y


y = y1+y2; %sequence Addition
Page
Digital Signal Processing Lab Manual

2- Signal multiplication:
This is a sample-by-sample multiplication (or "dot" multiplication) given by

{x1(n)}.{x2 (n)}  {x1(n) x2 (n)}

It is implemented in MATLAB by the array operator “.*”. Once again the similar
restrictions apply for the. * operator as for the + operator, Therefore we have
developed the sigmult function, which is similar to the sigadd function.

MATLAB FUNCTION
function [y,n] = sigmult(x1,n1,x2,n2)
%implements y(n) = x1(n)*x2(n)
%----------------------
% [y,n] = sigmult(x1,n1,x2,n2)
% y = product sequence over n. which includes n1 and n2
% x1 = first sequence over n1
% x2 = second sequence over n2 (n2 can be different from nl)
%
n = min(min(n1),min(n2)):max(max(n1),max(n2));%duration of y(n)
y1= zeros(1,length(n); y2 = y1; %
y1(find((n>=min(n1))&(n<=max(n1))==1))=x1; %x1 with duration of y
y2(find((n>=min(n2))&(n<=max(n2))==1))=x2; %x2 with duration of y
y = y1 .* y2; %sequence multiplication

3- Scaling: In this operation each sample is multiplied by a scalar α

 {x(n)}  {x(n)}

An arithmetic operator "*" is used to implement the scaling operation in MATLAB.

4- Shifting: In this operation each sample of x(n) is shifted by an amount k to obtain


a shifted sequence y(n)
y(n) = {x(n - k)}

If we let m == n - k, then n= m + k and the above operation is given by


y (m + k) = {x (m)}

Hence this operation has no effect on the vector x, but the vector n is changed by
adding k to each element, This is shown in the function sigshift.
41
Page
Digital Signal Processing Lab Manual

MATLAB FUNCTION
function [y,n] = sigshift(x,m,n0)
% implements y(n) = x(n-n0)
%-----------------------------------------
% [y,n] = sigshift(x,m,n0)
%
n =m+n0; y = x;

5- Folding:
In this operation each sample of x(n) is flipped around n = 0 to obtain a folded
sequence y(n).

y(n) = {x(-n)}

In MATLAB this operation is implemented by fliplr (x) function for sample values
and by -fliplr(n) function for sample positions as shown in the sigfold function

MATLAB FUNCTION
function [y,n] = sigfold(x,n)
% implements y(n) = x(-n)
% ----------------------¬
% [y,n] = sigfold(x,n)
y = fliplr(x); n = -fliplr(n);

6- Sample summation:
This operation differs from signal addition operation. It adds all sample values of
x(n) between n1 and n2

n2
 x(n)  x(n1)  .......... .  x(n2 )
n  n1
It is implemented by the sum(x (n1: n2)) function.

7- Sample products:
This operation also differs from signal multiplication operation. It multiplies all
sample values of x(n) between n1 and n2

n2
 x(n)  x(n1)  .......... .  x(n2 ) .
n  n1
42

It is implemented by the prod (x (n1 : n2)) function.


Page
Digital Signal Processing Lab Manual

8- Signal energy:
The energy of a sequence x(n) is given by

  2
 x   x(n)x (n)   x(n)
*
 

where superscript * denotes the operation of complex conjugation. The energy of a


finite-duration sequence x(n) can be computed in MATLAB using

>>Ex = sum(x .* conj(x)); % one approach

>>Ex = sum(abs(x) .^ 2); % another approach

9- Signal power:
The average power of a periodic sequence with fundamental period N is given by

1 N 1
x 
N
 x ( n) 2
0

Procedure:-
Execute following examples in MATLAB

EXAMPLE

Let
x(n)  {1,2,3,4,5,6,7,6,5,4,3,2,1}
. Determine and plot the following sequences.

a. x1 (n)  2x(n - 5) - 3x(n  4)


b. x 2 (n)  x(3 - n)  x(n)x(n - 2)
The sequence x (n) is nonzero over - 2  n  10 .
Hence

>> n = -2:10; x = [1:7,6:-1:1];

will generate x(n).

a. x1 (n)  2x(n - 5) - 3x(n  4)


43
Page
Digital Signal Processing Lab Manual

 The first part is obtained by shifting x(n) by 5 and the second part by shifting x(n)
by =-4.
 This shifting and the addition can be easily done using the sigshift and the sigadd
functions.

n = -2:10; x = [1:7,6:-1:1];
[x11,n11] = sigshift(x,n,5);
[x12,n12] = sigshift(x,n,-4);
[x1,n1] = sigadd(2*x11,n11,-3*x12,n12);
subplot(2,1,1); stem(n1,x1);title('Sequence in Examplea')
xlabel('n'); ylabel('x1(n)');

The plot of x1 (n) is shown in Figure a.

b. x 2 (n)  x(3 - n)  x(n)x(n - 2)


 The first term can be written as x(- (n - 3)). Hence it is obtained by first folding x
(n) and then shifting the result by 3.
 The second part is a multiplication of x (n) and x (n - 2), both of which have the
same length but different support (or sample positions). These operations can be
easily done using the sigfold and the sigmult functions.

>>[x21,n21] = sigfold(x,n);
>>[x21,n21] = sigshift(x21,n21,3);
>>[x22,n22] = sigshift(x,n,2);
>>[x22,n22] = sigmult(x,n,x22,n22);
>>[x2,n2] = sigadd(x21,n21,x22,n22);
>>subplot(2,1,2); stem(n2,x2);title('Sequence in Exampleb')
>>xlabel ('n'); ylabel('x2 (n) ') ;

The plot of x2(n) is shown in Figure b.

44
Page
Digital Signal Processing Lab Manual

Sequence in Examplea
20

10

0
x1(n)

-10

-20

-30
-10 -5 0 5 10 15
n

Sequence in Exampleb
40

30
x2 (n)

20

10

0
-8 -6 -4 -2 0 2 4 6 8 10 12
n

Assignment
Let
x(n) = {0 1 1 1 1 .5 .5} Generate and plot the samples

a) x(n-2)
b) x(4-n)
c) x(n+2)
d) x(n)u(2-n)
e) x(n-1)δ(n-3)
f) even part of x(n)
g) odd part of x(n)
Let
x(n)  {1,-2,4,6,-5,8,10}
. Generate and plot the samples (use the stem function) of the following

sequences.
a. x1 (n)  3x(n  2)  x(n - 4) - 2x(n)
b. x 2 (n)  5x(5  n)  4x(n  4)  3x(n)
c. x 3 (n)  x(n  4)x(n - 1)  x(2 - n)x(n)
d. x 4 (n)  2e0.5n x(n)  cos(0.1n)x(n  2), - 10  n  10
45

5
e. x 5 (n)   nx(n - k)
Page

k 1
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 7
Title: The Discrete-time Fourier Transform (DTFT)

Equipment Required: Personal computer (PC) with windows operating system and
MATLAB software
Introduction:-


If x(n) is absolutely summable, that is, n  
x(n)   , then its discrete- time
Fourier Transform is given by

X (e )  F[ x(n)] 
jw
 x(n)e
n  
 jwn

The inverse discrete-time Fourier transform (IDTFT) of X(ejw) is given by



x(n)  F 1 [ X (e jw )]   X (e jw )e  jwn d


The operator F[.] transforms a discrete signal x(n) into a complex-valued continues
function X(ejw) of real variable w, called the a digital frequency, which is measured in
radians.

1) MATLAB Implementation:-
If x(n) is of infinite duration, then MATLAB cannot be used directly to compute
jw
X(e ) from x(n). However, using Periodicity and Symmetry we can evaluate the
expression X (ejw) over [0, pi] frequencies and then plot its magnitude and angle (or real
and imaginary parts).

1. Periodicity: The discrete-time Fourier transform X(ejw) is periodic in ω with


period 2π

X (e jw )  X (e j w 2 )
Implication: We need only one period of X(ejw) (i.e.   [0,2 ], or[  ,  ] , etc.) for
46

analysis and not the whole domain       .


Page
Digital Signal Processing Lab Manual

2. Symmetry: For real-valued x(n), X(ejω) is conjugate symmetric.

X (e  j )  X  (e j )
Or

Re[ X (e  j )]  Re[ X (e j )] (even symmetry)

Im[ X (e  j )]   Im[ X (e j )] (odd symmetry)

X (e  j )  X (e j ) (even symmetry)

X (e j )  X (e j ) (odd symmetry)

Implication: To plot X(ejω), we now need to consider only a half period of X(ejω).
Generally, in practice this period is chosen to be   [0,  ]

2) DTFT Using Matrix Vector Multiplication:-


If x(n) is of finite duration, then MATLAB can be used to compute X(ejw) numerically
at any frequency w. The approach is to implement (3.1) directly. If, in addition, we
evaluate X(ejw) at equispaced frequencies between [0,π],then (3.1) can be implemented
as a matrix-vector multiplication operation. To understand this, let us assume that the
sequence x(n) has N samples between n1 ≤ n ≤ nN (i.e., not necessarily between [0,N -
1]) and that we want to evaluate X (ejw) at


k  k, k  0,1,........., M
M
which are (M + 1) equispaced frequencies between [0,π].Then (3.1) can be
written as

j k N  j ( / M ) knl
X (e ) e x ( nl ), k  0,1,......., M
l 1

When {x (nl)} and {X (ejwk)} are arranged as column vectors x and X, respectively, we have
X=Wx ……..(3)
47

where W is an (M + 1) × N matrix given by


Page
Digital Signal Processing Lab Manual

W  {e  j ( / M ) knl ; n1  n  nN , k  0,1,.... M }In


addition, if we arrange {k } and {nl} as row vectors k and n respectively, then

  
W  exp
 j kT n

  M 
In MATLAB we represent sequences and indices as row vectors; therefore taking the
transpose of (3),
T    T 
…….(4)
X T
 x  exp  j kn 
  M 

Note that nTk is an N× (M + 1) matrix. Now( 4) can be implemented in MATLAB as


follows.
k = [0:M]; n = [n1:n2];
X = x * (exp(-j*pi/M)) .^ (n'*k);

Procedure:-

Execute following Examples in MATLAB

1) Example:-
Evaluate the DTFT of x[n]=(0.5)n u(n) at 501 equispaced points between [0,π] and
plot its magnitude, angle, real, and imaginary parts.
The sequence x(n) is absolutely summable; therefore its discrete-time Fourier
transform exists.

  jwn 
X (e jw
)  x ( n )e   (0.5) n e  jwn
n   n 0
  jw 1 e jw
  (0.5e ) n
  jw
 jw
n 0 1  0.5e e  0.5
MATLABScript
w = [0:1:500]*pi/500; % [0, pi]axis divided into 501points.
X = exp(j*w) ./ (exp(j*w) - 0.5*ones(1,501));
magX = abs (X) ; angX = angle (X) ;
realX = real(X); imagX = imag(X);
subplot(2,2,1); plot(w/pi,magX); grid
48

xlabel('frequency in pi units'); title('Magnitude


Part');ylabel('Magnitude')
Page

subplot(2,2,3); plot(w/pi,angX); grid


Digital Signal Processing Lab Manual

xlabel('frequency in pi
units');title('AnglePart');ylabel('Radians')
subplot(2,2,2);plot(w/pi,realX);grid
xlabel('frequency in pi units'); title('Real Part');
ylabel('Real')
subplot(2,2,4); plot(w/pi,imagX); grid
xlabel('frequency in pi units'); title('Imaginary Part');
ylabel('Imaginary')

Magnitude Part Real Part


2 2

1.5 1.5
Magnitude

1 Real 1

0.5 0.5
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1
frequency in pi units frequency in pi units

AnglePart Imaginary Part


0 0

-0.2 -0.2
Imaginar
Radians

-0.4 -0.4

-0.6 -0.6

-0.8 -0.8
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1
frequency in pi units frequency in pi units

2) Example:-
Evaluate the DTFT of the following sequence x[n] at 501 equispaced frequencies
between [0,π]

X[n]=[1 2 3 4 5]

MATLABScript
n = -1:3; x = 1:5; %sequence x(n)
49

k = 0:500; w =(pi/500)*k;%[0,pi]axis divided into 501points


X = x * (exp(-j*pi/500)) .^ (n'*k);
Page

magX = abs(X); angX = angle(X);


Digital Signal Processing Lab Manual

realX = real(X); imagX = imag(X);


subplot(2,2,1); plot(k/500,magX);grid
xlabel('frequency in pi units'); title('Magnitude Part')
subplot(2,2,3); plot(k/500,angX/pi);grid
xlabel('frequency in pi units'); title('Angle Part')
subplot(2,2,2); plot(k/500,realX);grid
xlabel ( 'frequency in pi units'); title ('Real Part')
subplot(2,2,4); plot(k/500,imagX);grid
xlabel('frequency in pi units'); title('Imaginary part')

Magnitude Part Real Part


15 15

10
10

5
0

0 -5
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1
frequency in pi units frequency in pi units

Angle Part Imaginary part


1 5

0.5
0

-5
-0.5

-1 -10
0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1
frequency in pi units frequency in pi units

3) Example: -
Let x(n) = (0.9exp(jπ/3))n, 0 ≤ n ≤ 10 . Determine X(ejw) and investigate its periodicity.
Solution

Since x(n) is complex-valued, it satisfies only the periodicity property. Therefore it is


uniquely defined over one period of 2π. However, we will evaluate and plot it at 401
frequencies over two periods between [-2π,2π] to observe its periodicity.
50

MATLABScript
Page

n = 0:10; x = (0.9*exp(j*pi/3)).^n;
Digital Signal Processing Lab Manual

k = -200:200; w = (pi/100)*k;
X = x * (exp(-j*pi/100)).^(n'*k);
magX = abs(X); angX =angle(X);
subplot(2,1,1); plot(w/pi,magX);grid
xlabel('frequency in units of pi'); ylabel('|X|')
axis([-2,2,0,8])
title('Magnitude Part')
subplot(2,1,2); plot(w/pi,angX/pi);grid
xlabel('frequency in units of pi'); ylabel('radians/pi')
axis([-2,2,-.5,.5])
title('Angle Part')

Magnitude Part
8

6
|X|

0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency in units of pi

Angle Part
0.5
radians/pi

-0.5
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency in units of pi

4) Example:-
Let x(n)= (-0.9)n, -10 ≤n ≤ 10. Investigate the conjugate-symmetry property of its
discrete-time Fourier transform.
Solution
Once again we will compute and plot X(ejw) over two periods to study its
symmetry property.
51

MATLABScript
Page

n = -5:5; x = (-0.9).^n;
Digital Signal Processing Lab Manual

k = -200:200; w = (pi/100)*k;
X = x * (exp(-j*pi/100)) .^ (n'*k);
magX = abs(X); angX =angle(X)';
subplot(2,1,1); plot(w/pi,magX);grid
axis([-2,2,0,15])
xlabel('frequency in units of pi'); ylabel('|X|')
title('Magnitude Part')
subplot(2,1,2); plot(w/pi,angX/pi);grid
axis([-2,2,-1,1])
xlabel('frequency in units of pi'); ylabel('radians/pi')
title('Angle Part')

Magnitude Part
15

10
|X|

0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency in units of pi

Angle Part
1

0.5
radians/pi

-0.5

-1
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency in units of pi

52
Page

Problems
Digital Signal Processing Lab Manual

For each of the following sequences determine the DTFT X(w). plot the magnitude and
angle of X(w).
a) x(n) = {4,3,2,1,2,3,4}

b) x(n) = {4,3,2,1,2,3,4}

c) x(n) ={3,0,0,0,0,6,1,4}

d) x(n) = {1,1,0,1,1}

e) x(n) = {1,2,0,2,1}

53
Page
Digital Signal Processing Lab Manual

Faculty of Engineering
Experiment # 8
Title: Properties of DTFT
Equipment Required: Personal computer (PC) with windows operating system
and MATLAB software
Theory:-
1. Linearity:-

The discrete-time Fourier transform is a linear transformation, that is:

F[x1 (n)  x2 (n)]  [ Fx1 (n)]  F[ x2 (n)]


Where α and β are constant
2. Time shifting:-
A shift in the time domain corresponds to the phase shifting.

F [ x(n  k )]  X (e jw )e  jw

3. Frequency shifting:

Multiplication by a complex exponential corresponds to a shift in the frequency


domain.

F [ x(n)e jwo n ]  X (e j ( w wo ) n )

4. Conjugation:-

Conjugation in the time domain corresponds to the folding and conjugation in the
frequency domain.

F [ x * (n)]  X * (e  jw )

5. Folding:-

Folding in the time domain corresponds to the folding in the frequency domain.
54

F [ x(n)]  X (e  jw )
Page
Digital Signal Processing Lab Manual

6. Symmetries in real sequences:-


x[n]  xe [n]  xo (n)
Then
F{xe [n]}  Re{X (e jw )}
And
F{xo [n]}  jIM {X (e jw )}

Procedure:-

Execute following script fills in MATLAB Editor.


1) Verifying the Linearity property:-
In order to verify the linearity property, using real-valued finite duration sequences. Let
x1(n) and x2(n) be two random sequences uniformly distributed between [0, 1] over 0 ≤ n
≤10.
MATLAB Script File
xl = rand(1,11); x2 = rand(l,11); n = 0:10;
alpha = 2; beta= 3;
k = 0:500; w= (pi/500)*k;
X1 = x1 * (exp(-j*pi/500)).^(n'*k); %DTFT of x1
X2 = x2 * (exp(-j*pi/500)).^(n'*k); %DTFT of x2
x = alpha*xl + beta*x2; %Linear combinationof
x1&x2
X = x * (exp(-j*pi/500)).^(n'*k); % DTFT of x
% verification
X_check = alpha*X1 + beta*X2; %Linear Combinationof
X1&X2

error = max(abs(X-X_check)) % Difference


MATLAB Output:

2) Verify the sample shift property:-

Let x( n) be a random sequence, uniformly distributed between [0, 1] over 0 ≤ n≤ 10


and let y(n) = x(n - 2). Then we can verify the sample shift property (2) as follows.

MATLAB Script File


x = rand(1,11); n = 0:10;
55

k = 0:500; w = (pi/500)*k;
X = x * (exp(-j*pi/500)).^(n'*k); % DTFT of x
Page

% signal shifted by two samples


Digital Signal Processing Lab Manual

y = x; m = n+2;
Y = y* (exp(-j*pi/500)).^(m'*k); % DTFT of Y
% verification
Y_check = (exp(-j*2).^w).*X; % multiplication by exp(-j2w)
error = max(abs(Y-Y_check)) % Difference
MATLAB Output:

3) Verifying the Frequency shifting property:-


To verify the frequency shift property (3), we will use the graphical approach. Let
jn / 4
x ( n)  cos(n / 2), 0≤n≤100 and y ( n)  e x ( n)
Then using MATLAB,
MATLAB Script File
n = 0:100; x = cos(pi*n/2);
k = -100:100; w = (pi/100)*k; %frequency between -pi and
+pi
X = x * (exp(-j*pi/100)).^(n'*k);% DTFT of Jt
%
y = exp(j*pi*n/4).*x;% signal multiplied by exp(j*pi*n/4)
Y = y * (exp(-j*pi/100)).^(n'*k);% DTFT of Y
% Graphical verification
subplot(1,1,1)
subplot(2,2,1); plot(w/pi,abs(X)); grid; axis([-1,1,0,60])
xlabel('frequency in pi units'); ylabel('|X|')
title('Magnitude of X')
subplot(2,2,2); plot(w/pi,angle(X)/pi);grid; axis([-1,1,-
1,1])
xlabel('frequency in pi units'); ylabel('radiands/pi')
title('Angle of X')
subplot(2,2,3); plot (w/pi, abs(Y)); grid; axis([ -
1,1,0,60])
xlabel(' frequency in pi units'); ylabel('|Y| ')
title( 'Magnitude of Y')
subplot(2,2,4);plot(w/pi,angle(Y)/pi);grid;axis( [-1,1, -
1,1])
xlabel('frequency in pi units'); ylabel('radians/pi')
title('Angle of Y')

From plot we observe that X(ejw) is indeed shifted by pi/4 in both magnitude and angle
56
Page
Digital Signal Processing Lab Manual

Magnitude of X Angle of X
60 1

0.5

radiands/pi
40
|X|
0
20
-0.5

0 -1
-1 -0.5 0 0.5 1 -1 -0.5 0 0.5 1
frequency in pi units frequency in pi units
Magnitude of Y Angle of Y
60 1

0.5
40

radians/pi
|Y|

0
20
-0.5

0 -1
-1 -0.5 0 0.5 1 -1 -0.5 0 0.5 1
frequency in pi units frequency in pi units

Figure#1 Frequency shifting property

4) Verifying the Conjugation property


To verify the conjugation property (4), let x(n) be a complex-valued random
sequence over -5 ≤ n ≤ 10 with real and imaginary parts uniformly distributed between
[0,1]. The MATLAB verification is as follows.
MATLAB Script File
n = -5:10; x = rand(1,length(n)) + j*rand(1,length(n));
k = -100:100; w = (pi/100)*k; %frequency between -pi and
+pi
X = x * (exp(-j*pi/100)).^(n'*k);% DTFT of x
%conjugation property
y = conj(x); % signal conjugation
Y =y * (exp(-j*pi/100)).^(n'*k);%DTFT of y
% verification '
Y_check = conj(fliplr(X)); ,%conj(X(-w))
error = max(abs(Y-Y_check)) % Difference
57
Page

5) Verifying the Folding property


Digital Signal Processing Lab Manual

To verify the folding property (5), let x(n) be a random sequence over -5≤n≤10
uniformly distributed between [0,1]. The MATLAB verification is as

MATLAB Script File


n = -5:10; x = rand(1,length(n));
k = -100:100; w = (pi/100)*k; % frequency betveen -pi and
+pi
X = x * (exp(-j*pi/100)).^(n'*k);% DTFT of x
% folding property
y = fliplr(x); m = -fliplr(n); % Signal folding
Y = y * (exp(-j*pi/100)).^(m'*k);% DTFT of Y
% verification
Y_check = fliplr(X); % X(-w)
error = max(abs(Y-Y_check)) % Difference
MATLAB Output:

6) Verifying the Symmetries in real sequences property


To verify the symmetry property (6) of real signals, Let
x(n)  sin( n / 2), -5 ≤ n ≤ 10
Then using the evenodd function developed in experiment no 2, we can compute the
even and odd parts of x(n) and then evaluate their discrete-time Fourier transforms. We
will provide the numerical as well as graphical verification.
MATLAB Script File
n = -5:10; x = sin(pi*n/2);
k=-100:100; w=(pi/100)*k; % frequency between -pi and
+pi
X = x * (exp(-j*pi/100)).^(n'*k); % DTFT of x
% signal decomposition
[xe,xo,m] = evenodd(x,n); % even and odd parts
XE = xe * (exp(-j*pi/100)).^(m'*k); % DTFT of xe
XO = xo * (exp(-j*pi/100)).^(m'*k); % DTFT of xo
% verification
XR = real(X); % real part of X
errorl = max(abs(XE-XR)) % Difference
XI = imag(X); % imag part of X
error2 = max(abs(XO-j*XI)) % Difference
58

% graphical verification
subplot(1,1,1)
Page

subplot(2,2,1); plot(w/pi,XR); grid; axis([-1,1,-2,2])


Digital Signal Processing Lab Manual

xlabel('frequency in pi units'); ylabel('Re(X)');


title('Real part of X')
subplot(2,2,2); plot(w/pi,XI); grid; axis([-1,1,-10,10])
xlabel('frequency in pi units'); ylabel('Im(X)');
title('Imaginary part of X')
subplot (2,2,3); plot (w/pi ,real (XE)); grid;
axis ([-1,1, -2,2])
xlabel('frequency in pi units'); ylabel('XE');
title('Transform of even part')
subplot(2,2,4); plot(w/pi,imag(XO)); grid; axis([-1,1,-
10,10])
xlabel('frequency in pi units'); ylabel('XO');
title('Transform of odd part')

MATLAB Output:

Real part of X Imaginary part of X


2 10

1 5
Re(X)

Im(X)

0 0

-1 -5

-2 -10
-1 -0.5 0 0.5 1 -1 -0.5 0 0.5 1
frequency in pi units frequency in pi units

Transform of even part Transform of odd part


2 10

1 5
XO
XE

0 0

-1 -5

-2 -10
59

-1 -0.5 0 0.5 1 -1 -0.5 0 0.5 1


frequency in pi units frequency in pi units
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 9
Title: Discrete Time Transform (DFT)

Equipment Required: Personal computer (PC) with windows operating system


and MATLAB software
Theory:-
In Lab Experiment 7, we have discussed in detail the Discrete Time Fourier Transform
(DTFT) for the analysis of signals given by:

j
(DTFT):
X (e )   x( n)e  jn
n  
(1)

(IDTFT): 1  j jn (2)


x ( n)   X (e )e
2 

While DTFT is very useful analytically, it usually cannot be exactly evaluated on a


computer because equation (1) requires an infinite sum and equation (2) requires the
evaluation of an integral.

The discrete Fourier transform (DFT) is a sampled version of the DTFT, hence it is better
suited to numerical evaluation on computers

N 1
Analysis Equation (DFT): X (k )   x(n)e  j 2kn / N (3)
n 0

1 N 1 j 2kn / N
Synthesis Equation (lDFT): x ( n)   X ( k )e (4)
N k 0
Where X(k) is an N-point DFT of x[n]. Note that X(k)is a function of a discrete integer k,
60

where k ranges from 0 to N-1.


Page
Digital Signal Processing Lab Manual

Using the matrix vector multiplication technique used to compute the DTFT and DTFS in
previous laboratory experiments, we can calculate the DFT using:

WNnk  e  j 2kn / N
N 1
Equation (3) and (4) can be written as: X ( k )   x( n)WNnk (6)
n 0

1 N 1
Analysis Equation (DFT): x ( n)   X (k )WN
nk (7)
N k 0
Or equivalently,

X(k) = WNx(n)

x(n) =1/N WN*X(k)

WN is a square matrix. The following MATLAB function implements the above


procedure.
DFT Function

function [Xk] =dft (xn,N)


%ComputeDiscreteFourierTransform
n=[0:1:N-1];
k= [0:1:N-1];
WN = exp (-j * 2 * pi / N);
nk = n' * k;
WNnk = WN.^ nk;
Xk = xn * WNnk;

The following idft function implements the synthesis equation.


IDFT Function

function [xn] =idft (Xk, N)


%Compute Inverse Discrete Transform
n= [0:1:N-1];
61

k = [0:1:N-1];
WN = exp (-j * 2 * pi / N);
Page

nk = n' * k;
Digital Signal Processing Lab Manual

WNnk = WN .^ (-nk) ;
xn = (Xk * WNnk)/N;

Zero-Padding:-
It is an operation in which more zeros are appended to the original sequence. The
resulting longer DFT provides closely spaced samples of the discrete time Fourier
transform of the original sequence. In MATLAB zero padding is implemented using the
zeros function. The zero padding gives high-density spectrum and provides a better
displayed version for plotting. But it does not give a high resolution spectrum because
no new information is added to the signal: only additional zeros are added in the data.

Procedure:-
Execute following examples in MATLAB

EXAMPLE

To illustrate the difference between high-density spectrum and the high-resolution


spectrum consider the sequence

x(n) =cos(0.48πn) + cos(0.52πn)

a) High resolution spectrum based on 100 samples of the signal x(n)

subplot( 1,1,1)
n=[0:1:99];
x=cos(0.48 *pi *n)+cos(0.52 *pi *n);
subplot(2,1, 1);stem(n,x);
title('signal x(n), 0 <= n <= 99');xlabel('n')
axis([0, 100,-2.5,2.5])
X=fft(x);magX=abs(X(1: 1:51));
k=0:1:50;w=2*pi/100*k;
subplot(2,1 ,2);plot(w/pi,magX);title('DTFT
Magnitude');xlabel('frequency in pi units')
axis([0,1,0,60])
62
Page
Digital Signal Processing Lab Manual

signal x(n), 0 <= n <= 99

-1

-2

0 10 20 30 40 50 60 70 80 90 100
n

DTFT Magnitude
60

50

40

30

20

10

0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
frequency in pi units

b) Spectrum based on the first 10 samples of x(n)

n1=[0: 1:9];y1 =x( 1: 1: 10);


subplot(2,1, 1);stem(n1,y1);
title('signal x(n), 0 <= n <= 9');xlabel('n')
axis([0,10,-2.5,2.5])
Y1 =fft(y1);magY1 =abs(Y1( 1:1:6));
k1 =0:1:5;w1 =2*pi/10*k1;
subplot(2,1 ,2);stem(w1/pi,magY1 );
title('Samples of DTFT Magnitude');
xlabel('frequency in pi units')
axis([0,1 ,0, 10])
disp('Press RETURN to continue');pause;
63
Page
Digital Signal Processing Lab Manual

signal x(n), 0 <= n <= 99

-1

-2

0 10 20 30 40 50 60 70 80 90 100
n

DTFT Magnitude
60

50

40

30

20

10

0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
frequency in pi units

c) High density Spectrum (50 samples) based on the first 10 samples of x(n)

n2=[0:1:49];y2=[x(1: 1:10) zeros(1,40)];


subplot(2,1, 1);stem(n2,y2);
title('signal x(n), 0 <= n <= 9 + 40 zeros');xlabel('n')
axis([0,50, -2.5,2.5])
Y2=fft(y2);magY2=abs(Y2(1:1:26));
k2=0: 1:25;w2=2*pi/50*k2;
subplot(2,1 ,2);plot(w2/pi,magY2);
title('DTFT Magnitude');xlabel('frequency in pi units')
axis([0,1,0,10])
64
Page
Digital Signal Processing Lab Manual

signal x(n), 0 <= n <= 9 + 40 zeros

-1

-2

0 5 10 15 20 25 30 35 40 45 50
n

DTFT Magnitude
10

0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
frequency in pi units

d) High density spectrum (100 samples) based on the first 10 samples of x(n)

n3=[0: 1:99];y3=[ x(1: 1:10) zeros( 1,90)];


subplot(2,1, 1);stem(n3,y3);
title('signal x(n), 0 <= n <= 9 + 90 zeros');xlabel('n')
axis([0,100,-2.5,2.5])
Y3=fft(y3);magY3=abs(Y3(1: 1:51));
k3=0:1:50;w3=2*pi/100*k3;
subplot(2,1 ,2);plot(w3/pi,magY3);
title('DTFT Magnitude');xlabel('frequency in pi units')
axis([0, 1,0, 10])
65
Page
Digital Signal Processing Lab Manual

signal x(n), 0 <= n <= 9 + 90 zeros

-1

-2

0 10 20 30 40 50 60 70 80 90 100
n

DTFT Magnitude
10

0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
frequency in pi units

PROBLEMS .
1) Determine the DFT of the following periodic sequences using the DFT definition,
and verify by using MATLAB.
a. x1(n)={2,0,2,0},N=4
b. x2(n) = {0,0, 1,0, 0}, N = 5
c. X3(n) = {3, -3,3, -3}, N = 4
d. x4(n) = {j,j, -j, -j}, N = 4
e. x5(n) = {1,j,j, 1}, N = 4

2) Determine the x(n), First use the IDFS definition and then verify' using MATLAB.
a. X1(k) = {5, -2j, 3, 2j}, N = 4
b. X2(k)={4,-5,3,-5},N=4
c. X3(k)={I,2,3,4,5},N=5
66

d. X4(k)={0,0,2,0},N=4
Page

e. X5 (k) = {0,j, -2j, -j}, N = 4


Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 10
Title: Amplitude Modulation (AM)
Equipment Required: Personal computer (PC) with windows operating system
and MATLAB software
Objective:
The objective of this lab is to illustrate an amplitude modulation (AM) scheme

Definition:
Amplitude modulation is define as a process in which the amplitude of the carrier
wave c(t) is varied about a mean value, linearly with the message signal m(t)

Theory:
Consider a sinusoidal carrier wave c(t) defined by
c(t )  Ac cos(2f c t )
Where Ac is the carrier amplitude and fc is the carrier frequency.
The amplitude-modulated (AM) wave is described as a function of time as follow
s(t )  Ac [1  k a m(t )] cos(2f c t ) (1)
Where m(t) is the message and ka is a constant called amplitude sensitivity of the
modulator responsible for generation of the modulated signal s(t)
In amplitude modulation, information pertaining to the message signal m(t)
resides solely in the envelope, which is defined as the amplitude of the modulated wave
s(t)-that is, Ac [1  ka m(t )] . From this expression, we observe that the envelope of s(t) has
essentially the same shape as the message signal m(t) provided that two conditions are
satisfied:
1. The amplitude of k a m(t ) is always less than unity; that is,

k a m(t )  1 for all t

This condition is illustrated in Fig. 1(b); it ensures that the function 1 + kam(t) is
always positive. When the amplitude sensitivity ka of the modulator is large enough to
make k a m(t )  1 for any t, the carrier wave become over modulated, resulting in carrier
67

phase reversals whenever the factor 1  k a m(t ) crosses zero. The modulated wave then
Page

exhibits envelope distortion, as in Fig. 1(c).


Digital Signal Processing Lab Manual

2. The carrier frequency fc is much greater than the highest frequency component W
of the message signal m( t ),that is
f c  W
We call W the message bandwidth. If the condition of above equation is not
satisfied, an envelope cannot be visualized (and therefore detected) satisfactorily

Fig.1. illustration of the amplitude modulation process. (a) message signal m(t).
(b) Am wave for k a m(t )  1 for all t (c). AM wave for k a m(t )  1 for some t
68
Page
Digital Signal Processing Lab Manual

Implementation of Amplitude Modulation in CCS:


The buffer baseband contains 20 points and represents a baseband cosine signal
with a frequency of f = Fs/20 = 400Hz. The buffer carrier contains 4 points and
represents a carrier signal with a frequency of f = Fs/(number points per cycle) =
8000/4=2kHz. The output equation shows the baseband signal being modulated by the
carrier signal. The variable amp is used to vary the modulation. The polling-driven C
source program AM.c implements this project.
The amplitude of information signal varies between +1000 and -1000, to make
k a m(t )  1
k a 1000  1
1
ka  , ka should be less then .001
1000
The output consists of the 2-kHz carrier signal and two sideband signals. The
sideband signals are at the frequency of the carrier signal + or - the frequency of the
sideband signal, or at 1600 and 2400Hz.

Procedure:
1. To create the project file. Select Project  New. Type AM for the project name.
This project file is saved in the folder AM (within D:\program
files\myprojects).

2. To add files to the project. Select Project  Add Files to Project. Look in the
folder support, Files of type C Source Files. Double-click on the C source file
C6713dskinit.c to add it to the project. Click on the “+” symbol to the left of the
69

Project Files window within CCS to expand and verify that this C source file has
been added to the project.
Page
Digital Signal Processing Lab Manual

3. Repeat step 2, use the pull-down menu for Files of type, and select ASM Source
Files. Double-click on the assembly source vector file vectors_poll.asm to add it
to the project. Repeat again and select Files of type: Linker Command File, and
add C6713dsk.cmd to the project.
4. To add the library support files to the project. Repeat the previous step, but
select files of type: Object and Library Files.
I. Look in D:\program files\c6000\cgtools\lib and select the
run-time support library file rts6700.lib (which supports the C67x
architecture) to add to the project.
II. Continue this process to add the BSL file dsk6713bsl.lib located in
D:\program files \c6000\dsk6713\lib,
III. The chip support library (CSL) file csl6713.lib located in D:\program
files \c6000\csl\lib.
5. Select File  New  Source File. This will open CCS editor, type the following
program in it and save it with name AM.C
Amplitude modulation program (AM.c).
//AM.c AM using table for carrier and baseband signals
#include "C:\CCStudio_v3.1\C6000\dsk6713\include\DSK6713_AIC23.h"
//codec-dsk support file
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling rate
float amp = .0001;
short baseband[200]; //index for modulation
short output_buffer[200];
short carrier[200];
void main()
{
short k;
short baseband[200]={1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-309 ,0,309,587,809,
951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951,
1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-
309,0,309,587,809,951};
//400-Hz baseband
short carrier[200]={1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
70

1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
Page

1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
Digital Signal Processing Lab Manual

1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0, 1000,0,-1000,0,
1000,0,-1000,0};//2-kHz carrier

comm_poll(); //init DSK, codec, McBSP


while(1) //infinite loop
{
for (k=0; k<200; k++)
{
output_buffer[k]= carrier[k]*(1+amp*baseband[k]);
}
}
}
_______________________________________________________________________________________________________________

6. Compiler Option
Select Project  Build Options. Figure 1.4a shows the CCS window Build
Options for the compiler.
I. Select the following for the compiler option with Basic (for Category):
a) c671x{-mv6710} (for Target Version),
b) Full Symbolic Debug (for Generate Debug Info),
c) Speed most critical (for Opt Speed vs. Size),
d) None (for Opt Level and Program Level Opt).
II. Select the Preprocessor Category and type for Define Symbols{d}:
CHIP_6713
III. Select the Files Category and type for Obj Directory(-fr) D:\Program
files\My Projects\AM\Debug
IV. Select the Advanced Category and select for Memory Models Far 71
Page
Digital Signal Processing Lab Manual

7. Linker Option
Click on Linker (from CCS Build Options).The output filename AM.out defaults
to the name of the .pjt filename, and Run-time Autoinitialization defaults for
Autoinit Model. The -c option is used to initialize variables at run time, and the -o
option is used to name the linked executable output file AM.out. Press OK

72
Page
Digital Signal Processing Lab Manual

8. Building and Running the Project


I. Select Project  Rebuild All or press the toolbar with the three down
arrows . This creates an executable file AM.out that can be loaded into
the C6713 processor and run. Note that the commands for compiling,
assembling, and linking are performed with the Build option. A log file
cc_build_Debug.log is created that shows the files that are compiled and
assembled, along with the compiler options selected. It also lists the support
functions that are used.
II. Select File  Load Program in order to load AM.out by clicking on it (CCS
includes an option to load the program automatically after a build). It should
be in the folder AM\Debug. Select Debug  Run or use the toolbar with the
“running man.”
9. Plotting with CCS
Select View  GraphTime/Frequency.
I. Carrier wave plots
73

 Time-domain plot
Page
Digital Signal Processing Lab Manual

Change the Graph Property Dialog so that the options in Figure 2 are
selected for a time-domain plot (use the pull-down menu when
appropriate).The starting address of the output buffer is carrier. The other
options can be left as default. Figure 3 shows a time-domain plot of the
sinusoidal signal within CCS.
 Frequency-domain plot
Figure 2.b shows CCS’s Graph Property Display for a frequency-domain
plot. Choose a fast Fourier transform (FFT) order so that the frame size is
2order. Press OK and verify that the FFT magnitude plot is as shown in
Figure 3. The spike at 2000 Hz represents the frequency of the sinusoidal
carrier wave generated.

(a)

74
Page
Digital Signal Processing Lab Manual

(b)
Figure 2 CCS Graph Property Dialog for carrier wave (a) for time-
domain plot; (b) for frequency-domain plot.

Figure 3. CCS windows for carrier wave showing both time and frequency domain plots
of a generated 2kHz sine wave

II. Information bearing signal plots


 Time-domain plot
Same as in previous step but change the starting address of the output
buffer to baseband. The other options can be left as default.
 Frequency-domain plot
75
Page
Digital Signal Processing Lab Manual

Choose a fast Fourier transform (FFT) order so that the frame size is
2order. Press OK. The spike at 400 Hz represents the frequency of the
information bearing signal.

Figure 4. CCS windows for information bearing signal showing both time and frequency
domain plots of a generated 400Hz sine wave
III. Amplitude modulated signal plots
 Time-domain plot
Same as in previous step but change the starting address of the output
buffer to output_buffer. The other options can be left as default.
 Frequency-domain plot
Choose a fast Fourier transform (FFT) order so that the frame size is 2 order.
Press OK. The spike at 2000Hz represents the frequency of the carrier
signal. The spikes at 1600Hz and 2400Hz represent the fc-fm and fc+fm (ie
2000-400 and 2000+400)

Figure 5. CCS windows for Amplitude Modulated signal showing both time and
frequency domain plots
76

Reference:
(1) Introduction to Analog and Digital Communication (Simon Haykin, Michael
Page

Moher)
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 11
Title: Discrete Fourier Transform (DFT)
Equipment Required: Personal computer (PC) with windows operating system
and MATLAB software
Objective:
The objective of this lab is to implement Discrete Fourier Transform on DSK 6713
Introduction:
Figure 2 shows a listing of the program DFT.c, which implements the DFT. The input
sequence is x(n). The program calculates
N 1
X (k )  DFT {x(n)}   x(n)e 2nk / N k  0,1,2,..........N - 1 ……………(1)
n 0

This can be decomposed into a sum of real components and a sum of imaginary components,

Let

e  j 2kn / N 
2

1  j 2kn / N
e  e  j 2kn / N 

2
e 
1  j 2kn / N
 e  j 2kn / N  e j 2nk / N  e j 2kn / N 
1
2
 1

 e  j 2kn / N  e  j 2kn / N  (e j 2kn / N  e  j 2kn / N )
2
where
1 1 jw  jw 1
cos(w)  (e jw  e  jw ) and sin(w)  (e  e )  j sin(w)  (e jw  e  jw )
2 2j 2
e  j 2kn / N  cos(2kn / N )  j sin(2kn / N )
Eq (1) can be re written as:
77

N 1
X (k )  DFT {x(n)}   x(n)cos(2kn / N )  j sin(2kn / N )  k  0,1,2,..........N - 1
Page

n 0
Digital Signal Processing Lab Manual

Or
N 1
Re{X (k )}   x(n) cos(2kn / N )
n 0
And
N 1
Im{ X (k )}   x(n) sin(2nk / N )
n 0

Procedure:
1. To create the project file. Select Project  New. Type DFT for the project name. This
project file is saved in the folder DFT (within D:\program files\myprojects).

Figure -1 Code Composer Studio project creation Window

2. To add files to the project. Select Project  Add Files to Project. Look in the folder
support, Files of type Linker command files. Double-click on the Linker command file
C6713dsk.cmd to add it to the project. Click on the “+” symbol to the left of the Project
Files window within CCS to expand and verify that this Linker command file has been
added to the project.
3. Select File  New  Source File. This will open CCS editor, type the following
program in it and save it, in folder D:\program files\myprojects\DFT with
name DFT.C. 78
Page
Digital Signal Processing Lab Manual

Discrete Fourier Transform program (DFT.c).


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

#include <stdio.h>
#include <math.h>
void dft(short *input, short k, float *out,float *outim);//function
prototype
#define N 6 //number of data
values
float pi = 3.1416;
int j;
short input[N] = {1,1,2,2,3,3};

float out[6] = {0,0,0,0,0,0}; //init Re and Im


results
float outim[6] = {0,0,0,0,0,0};
void dft(short *input, short k, float *out,float *outim) //DFT
function
{
float sumRe = 0, sumIm = 0; //init real/imag
components
float cs = 0, sn = 0; //init cosine/sine
components
int i = 0;
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 + input[i]*cs; //sum of real components
sumIm = sumIm - input[i]*sn; //sum of imaginary components
}
out[k] = sumRe; //sum of real components
outim[k] = sumIm; //sum of imaginary components
}

void main()
{
int j;
while(1)
{
for (j = 0; j < N; j++)
{
dft(input,j,out,outim); //call DFT function
}
}
}
79

_______________________________________________________________________________________________________________
Page

FIGURE 2. DFT implementation program with input from a lookup table (DFT.c).
Digital Signal Processing Lab Manual

4. Add C source file DFT.c to the project.


5. Compiler Option
Select Project  Build Options. Figure 2.4a shows the CCS window Build Options
for the compiler.
I. Select the following for the compiler option with Basic (for Category):
a) c671x{-mv6710} (for Target Version),
b) Full Symbolic Debug (for Generate Debug Info),
c) Speed most critical (for Opt Speed vs. Size),
d) None (for Opt Level and Program Level Opt).
II. Select the Preprocessor Category and type for Define Symbols{d}: CHIP_6713
III. Select the Files Category and type for Obj Directory(-fr) D:\Program
files\My Projects\DFT\Debug

Figure-3 CCS Build options: compiler.

6. Linker Option
Click on Linker (from CCS Build Options).
80

I. Select the following for the compiler option with Basic (for Category):
Page

a) Select Suppress banner


Digital Signal Processing Lab Manual

b) Select Exhaustively Read Library


c) For Output Filename (-o) type .\Debug\DFT.out
d) For Map Filename (-o) type .\Debug\DFT.map
e) For Autoinit Model: Select Run-Time Autoinitialization(-c)
f) For include Libraries type rts6700.lib
II. Click on the Advanced options
a) De-select Warn About Output Sections(-w)

Figure-4 CCS Build options: linker.

7. Building and Running the Project


I. Select Project  Rebuild All or press the toolbar with the three down arrows .
This creates an executable file DFT.out that can be loaded into the C6713 processor
and run. Note that the commands for compiling, assembling, and linking are
performed with the Build option. A log file cc_build_Debug.log is created that
shows the files that are compiled and assembled, along with the compiler options
selected. It also lists the support functions that are used.
81

II. Select File  Load Program in order to load DFT.out by clicking on it (CCS
includes an option to load the program automatically after a build). It should be in
Page
Digital Signal Processing Lab Manual

the folder DFT\Debug. Select Debug  Run or use the toolbar with the “running
man.”
8. Monitoring the Watch Window
Select View  Quick Watch window, which should be displayed on the lower section of
CCS. Type input, then click on “Add to Watch.” This will display the input sequence on
which the DFT is to be performed.

Figure 5 CCS Quick Watch Dialog for input sequence

Again Select View  Quick Watch window, Type out, then click on “Add to Watch.” This will
display the real part of the output vector.

Figure 6 CCS Quick Watch Dialog for real part of output vector

Again Select View  Quick Watch window, Type outim, then click on “Add to Watch.” This
will display the imaginary part of the output vector.
82
Page
Digital Signal Processing Lab Manual

Figure 7 CCS Quick Watch Dialog for imaginary part of output vector
Right click on the quick watch window and select the option Float in Main Window.

And maximize the window

83
Page
Digital Signal Processing Lab Manual

Assignment#1

Calculate the DFT of the sample data sequence x(n) = {1, 2, 3, 4, 5, 6}

(i) Using Code Composer Studio

(ii) Verify the result using MATLAB.

Assignment#2

Calculate the DFT of the sample data sequence x(n) = {1, -1, 2, 1, -1, 3}

(i) Using Code Composer Studio

(ii) Verify the result using MATLAB.

Reference:

(2) Introduction to Analog and Digital Communication (Simon Haykin, Michael Moher)
(3) Digital Signal Processing and Applications with the C6713 and C6416 DSK (Rulph
Chassaing)
84
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 12
Title: Binary Phase Shift Keying
Equipment Required: Personal computer (PC) with windows operating system
and MATLAB software
Definition:
Binary Phase Shift Keying is a form of digital modulation in which the carrier amplitude
and carrier frequency are both maintained constant, while carrier phase is keyed between the two
possible values (e.g, 0˚ and 180˚) used to represent symbol 0 and 1.

Theory:
The simplest scheme uses two phases to represent the two binary digits and is known as
binary phase shift keying. The resulting transmitted signal for one bit time is

 A cos(2f c t )  A cos(2f c t ) binary 1


s(t )    (1)
 A cos(2f c t   )  A cos(2f c t ) binary 0
Because a phase shift of 180˚ (π) is equivalent to flipping the sine wave or multiplying it
by -1, the right most expressions in equation (1) can be used. This leads to a convenient
formulation. If we have a bit stream, and we define d(t) as the discrete function that takes on the
values of +1 for one bit time if the corresponding bit stream is 1 and the vale of -1 for one bit
time if the corresponding bit in the bit stream is 0, then we can define the transmitted signal as

s d (t )  A  d (t )  cos(2f c t ) (2)

Binary d(t) BPSK


Non-return to zero Product
data Signal
level encoder modulator
stream

Carrier
85

Figure 1 BPSK Modulator


Page
Digital Signal Processing Lab Manual

Procedure:
1. To create the project file. Select Project  New. Type BPSK for the project name. This
project file is saved in the folder BPSK (within D:\program
files\myprojects).

Figure-2 CCS Project Creation Window for BPSK

2. To add files to the project. Select Project  Add Files to Project. Look in the folder
support, Files of type C Source Files. Double-click on the C source file C6713dskinit.c to
add it to the project. Click on the “+” symbol to the left of the Project Files window
within CCS to expand and verify that this C source file has been added to the project.
3. Repeat step 2, use the pull-down menu for Files of type, and select ASM Source Files.
Double-click on the assembly source vector file vectors_poll.asm to add it to the project.
Repeat again and select Files of type: Linker Command File, and add C6713dsk.cmd to
the project.
4. To add the library support files to the project. Repeat the previous step, but select files of
type: Object and Library Files.
I. Look in D:\program files\c6000\cgtools\lib and select the run-time
support library file rts6700.lib (which supports the C67x architecture) to add to the
project.
II. Continue this process to add the BSL file dsk6713bsl.lib located in D:\program
files \c6000\dsk6713\lib,
III. The chip support library (CSL) file csl6713.lib located in D:\program files
\c6000\csl\lib.

5. Select File  New  Source File. This will open CCS editor, type the following
86

program in it and save it in the folder Myproject\BPSK with name BPSK.C


Page

Binary Phase Shift Keying program (BPSK.c).


Digital Signal Processing Lab Manual

______________________________________________________________________________
#include
"C:\CCStudio_v3.1\C6000\dsk6713\include\DSK6713_AIC23.h"
//codec-dsk support file
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling
rate
short bpsk_signal[200];
short carrier[20];
void main()
{
short k=0,i=0,j=0;
short carrier[20]={1000,951,809,587,309,0,-309,-587,-809,-951,-
1000,-951,-809,-587,-309,0,309,587,809,951};
//400Hz carrier
short data[10]={1,-1,1,-1,1,-1,1,-1,1,-1};
comm_poll(); //init DSK, codec,
McBSP
while(1) //infinite loop
{
for (k=0; k<10; k++)
{
if(data[k]>0) //to check input data(if
+1)
for(i=0;i<20;i++)
{
bpsk_signal[j] = carrier[i];
j++;
}

else //else input data is -1


for(i=0;i<20;i++)
{
bpsk_signal[j] = -1*carrier[i];
j++;
}
if(j>199)
j=0;
}
}
}_______________________________________________________________

6. Compiler Option
Select Project  Build Options. Figure 1.4a shows the CCS window Build Options
for the compiler.
87

I. Select the following for the compiler option with Basic (for Category):
a) c671x{-mv6710} (for Target Version),
Page

b) Full Symbolic Debug (for Generate Debug Info),


Digital Signal Processing Lab Manual

c) Speed most critical (for Opt Speed vs. Size),


d) None (for Opt Level and Program Level Opt).
II. Select the Preprocessor Category and type for Define Symbols{d}: CHIP_6713
III. Select the Files Category and type for Obj Directory(-fr) D:\Program
files\My Projects\BPSK\Debug
IV. Select the Advanced Category and select for Memory Models Far

Figure-3 CCS Build options: compiler.

7. Linker Option
Click on Linker (from CCS Build Options).
I. Select the following for the compiler option with Basic (for Category):
a) Select Suppress banner
b) Select Exhaustively Read Library
c) For Output Filename (-o) type .\Debug\BPSK.out
d) For Map Filename (-o) type .\Debug\BPSK.map
e) For Autoinit Model: Select Run-Time Autoinitialization(-c)
88
Page
Digital Signal Processing Lab Manual

Figure-4 CCS Build options: linker.

8. Building and Running the Project


I. Select Project  Rebuild All or press the toolbar with the three down arrows .
This creates an executable file BPSK.out that can be loaded into the C6713
processor and run. Note that the commands for compiling, assembling, and linking
are performed with the Build option. A log file cc_build_Debug.log is created that
shows the files that are compiled and assembled, along with the compiler options
selected. It also lists the support functions that are used.
II. Select File  Load Program in order to load BPSK.out by clicking on it (CCS
includes an option to load the program automatically after a build). It should be in
the folder BPSK\Debug. Select Debug  Run or use the toolbar with the “running
man.”
9. Plotting with CCS
Select View  GraphTime/Frequency.
IV. BPSK Signal plot
 Time-domain plot
89

Change the Graph Property Dialog so that the options in Figure 5 are selected
for a time-domain plot (use the pull-down menu when appropriate).The starting
Page

address of the output buffer is bpsk_signal. The other options can be left as
Digital Signal Processing Lab Manual

default. Figure 6 shows a time-domain plot of the Binary Phase shifted signal
within CCS.

(a)
Figure 5 CCS Graph Property Dialog for BPSK Signal’s time-domain plot

90
Page
Digital Signal Processing Lab Manual

Figure 6. CCS windows for BPSK Signal showing time domain plot

10. Monitoring the Watch Window


Select View  Quick Watch window, which should be displayed on the lower section of CCS.
Type Data, and then click on “Add to Watch.” This will display the input data sequence.

Figure 7 CCS Quick Watch Dialog for input binary data

Compare the input data with the plot


91
Page
Digital Signal Processing Lab Manual

Assignment #1

Change the input data values to {-1 ,-1,-1,-1,-1,1,1,1,1,1} and plot the generated signal using
CCS

Reference:

(1) Introduction to Analog and Digital Communication (Simon Haykin, Michael Moher)
(2) Digital Signal Processing and Applications with the C6713 and C6416 DSK (Rulph
Chassaing)
(3) Wireless Communications and networks (William Stallings)
92
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 13
Title: Binary Amplitude Shift Keying
Equipment Required: Personal computer (PC) with windows operating system
and MATLAB software

Definition:
Binary Amplitude Shift Keying is a form of digital modulation in which the carrier
frequency and carrier phase are both maintained constant, while carrier amplitude is keyed
between the two possible values used to represent symbols 0 and 1.

Theory:
In Amplitude Shift keying, the two binary values are represented by two different
amplitudes of the carrier frequency. Commonly, one of the amplitude is zero; that is, one binary
digit is represented by the presence, at constant amplitude, of the carrier, the other by the absence
of the carrier. The resulting transmitted signal for one bit time is

 A cos(2f c t ) binary 1
s(t )   (1)
 0 binary 0

where the carrier signal is A cos(2πfct). Ask is susceptible to sudden gain changes and is
a rather inefficient modulation technique. On Voice-grade lines, it is typically used up to 1200
bps

Procedure:
1. To create the project file. Select Project  New. Type BASK for the project name. This
project file is saved in the folder BASK (within D:\program
files\myprojects).
93
Page
Digital Signal Processing Lab Manual

Figure-2 CCS Project Creation Window for BASK

2. To add files to the project. Select Project  Add Files to Project. Look in the folder
support, Files of type C Source Files. Double-click on the C source file C6713dskinit.c to
add it to the project. Click on the “+” symbol to the left of the Project Files window
within CCS to expand and verify that this C source file has been added to the project.
3. Repeat step 2, use the pull-down menu for Files of type, and select ASM Source Files.
Double-click on the assembly source vector file vectors_poll.asm to add it to the project.
Repeat again and select Files of type: Linker Command File, and add C6713dsk.cmd to
the project.
4. To add the library support files to the project. Repeat the previous step, but select files of
type: Object and Library Files.
I. Look in D:\program files\c6000\cgtools\lib and select the run-time
support library file rts6700.lib (which supports the C67x architecture) to add to the
project.
II. Continue this process to add the BSL file dsk6713bsl.lib located in D:\program
files \c6000\dsk6713\lib,
III. The chip support library (CSL) file csl6713.lib located in D:\program files
\c6000\csl\lib.

5. Select File  New  Source File. This will open CCS editor, type the following
program in it and save it in the folder Myproject\BASK with name BASK.C
6. Add BASK.C file to the project 94
Page
Digital Signal Processing Lab Manual

Binary Amplitude Shift Keying program (BASK.c).


______________________________________________________________________________
#include
"C:\CCStudio_v3.1\C6000\dsk6713\include\DSK6713_AIC23.h"
//codec-dsk support file
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling
rate
short bask_signal[200];
short carrier[20];
void main()
{
short k=0,i=0,j=0;
short carrier[20]={1000,951,809,587,309,0,-309,-587,-809,-951,-
1000,-951,-809,-587,-309,0,309,587,809,951};
//400Hz carrier
short data[10]={1,-1,1,-1,1,-1,1,-1,1,-1};
comm_poll(); //init DSK, codec,
McBSP
while(1) //infinite loop
{
for (k=0; k<10; k++)
{
if(data[k]>0) //to check input data(if
+1)
for(i=0;i<20;i++)
{
bask_signal[j] = carrier[i];
j++;
}

else //else input data is -1


for(i=0;i<20;i++)
{
bask_signal[j] = 0 ;
j++;
}
if(j>199)
j=0;
}
}
}_______________________________________________________________

7. Compiler Option
Select Project  Build Options. Figure 3 shows the CCS window Build Options for
95

the compiler.
I. Select the following for the compiler option with Basic (for Category):
Page

a) c671x{-mv6710} (for Target Version),


Digital Signal Processing Lab Manual

b) Full Symbolic Debug (for Generate Debug Info),


c) Speed most critical (for Opt Speed vs. Size),
d) None (for Opt Level and Program Level Opt).
II. Select the Preprocessor Category and type for Define Symbols{d}: CHIP_6713
III. Select the Files Category and type for Obj Directory(-fr) D:\Program
files\My Projects\BASK\Debug
IV. Select the Advanced Category and select for Memory Models Far

Figure-3 CCS Build options: compiler.

8. Linker Option
Click on Linker (from CCS Build Options).
I. Select the following for the compiler option with Basic (for Category):
a) Select Suppress banner
b) Select Exhaustively Read Library
c) For Output Filename (-o) type .\Debug\BASK.out
d) For Map Filename (-o) type .\Debug\BASK.map
e) For Autoinit Model: Select Run-Time Autoinitialization(-c)
96
Page
Digital Signal Processing Lab Manual

Figure-4 CCS Build options: linker.

9. Building and Running the Project


I. Select Project  Rebuild All or press the toolbar with the three down arrows .
This creates an executable file BASK.out that can be loaded into the C6713
processor and run. Note that the commands for compiling, assembling, and linking
are performed with the Build option. A log file cc_build_Debug.log is created that
shows the files that are compiled and assembled, along with the compiler options
selected. It also lists the support functions that are used.
II. Select File  Load Program in order to load BASK.out by clicking on it (CCS
includes an option to load the program automatically after a build). It should be in
the folder BASK\Debug. Select Debug  Run or use the toolbar with the “running
man.”
10. Plotting with CCS
Select View  GraphTime/Frequency.
V. BASK Signal plot
 Time-domain plot
97

Change the Graph Property Dialog so that the options in Figure 5 are selected
for a time-domain plot (use the pull-down menu when appropriate).The starting
Page

address of the output buffer is bask_signal. The other options can be left as
Digital Signal Processing Lab Manual

default. Figure 6 shows a time-domain plot of the Binary Amplitude shifted signal
within CCS.

Figure 5 CCS Graph Property Dialog for BASK Signal’s time-domain plot

98
Page

Figure 6. CCS windows for BASK Signal showing time domain plot
Digital Signal Processing Lab Manual

11. Monitoring the Watch Window


Select View  Quick Watch window, which should be displayed on the lower section of CCS.
Type Data, and then click on “Add to Watch.” This will display the input data sequence.

Figure 7 CCS Quick Watch Dialog for input binary data

Compare the input data with the plot

99
Page
Digital Signal Processing Lab Manual

Assignment #1

Change the input data values to {-1 -1, 1, 1,-1,-1, 1, 1,-1,-1} and plot the generated signal using
CCS

Reference:

(1) Introduction to Analog and Digital Communication (Simon Haykin, Michael Moher)
(2) Digital Signal Processing and Applications with the C6713 and C6416 DSK (Rulph
100

Chassaing)
(3) Wireless Communications and networks (William Stallings)
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 14
Title: Linear Convolution
Equipment Required:
TMS 320C6713 Kit.
RS232 Serial Cable
Power Cord
AIM
To verify Linear Convolution
THEORY

Convolution is a formal mathematical operation, just as multiplication, addition, and integration.


Addition takes two numbers and produces a third number, while convolution takes two signals
and produces a third signal. Convolution is used in the mathematics of many fields, such as
probability and statistics. In linear systems, convolution is used to describe the relationship
between three signals of interest: the input signal, the impulse response, and the output signal.

In this equation, x1(k), x2 (n-k) and y(n) represent the input to and output from the system at
time n. Here we could see that one of the input is shifted in time by a value everytime it is
multiplied with the other input signal. Linear Convolution is quite often used as a method of
implementing filters of various types.

ALGORITHM

Step 1 Declare three buffers namely Input buffer, Temporary Buffer, Output Buffer.
Step 2 Get the input from the CODEC, store it in Input buffer and transfer it to the first location
of the
Temporary buffer.
Step 3 Make the Temporary buffer to point to the last location.
Step 4 Multiply the temporary buffer with the coefficients in the data memory and accumulate it
with
the previous output.
Step 5 Store the output in the output buffer.
Step 6 Repeat the steps from 2 to 5.
101

Procedure:
1. To create the project file. Select Project  New. Type Convolution for the project
name. This project file is saved in the folder Convolution (within D:\program
Page

files\myprojects).
Digital Signal Processing Lab Manual

2. To add files to the project. Select Project  Add Files to Project. Look in the folder
support, Files of type C Source Files. Double-click on the C source file C6713dskinit.c to
add it to the project. Click on the “+” symbol to the left of the Project Files window
within CCS to expand and verify that this C source file has been added to the project.
3. Repeat step 2, use the pull-down menu for Files of type, and select ASM Source Files.
Double-click on the assembly source vector file vectors_poll.asm to add it to the project.
Repeat again and select Files of type: Linker Command File, and add C6713dsk.cmd to
the project.
4. To add the library support files to the project. Repeat the previous step, but select files of
type: Object and Library Files.
I. Look in D:\program files\c6000\cgtools\lib and select the run-time
support library file rts6700.lib (which supports the C67x architecture) to add to the
project.
II. Continue this process to add the BSL file dsk6713bsl.lib located in D:\program
files \c6000\dsk6713\lib,
III. The chip support library (CSL) file csl6713.lib located in D:\program files
\c6000\csl\lib.
5. Select File  New  Source File. This will open CCS editor, type the following
program in it and save it with name Convolution.c
Convolution program (Convolution.c).
#include
"C:\CCStudio_v3.1\C6000\dsk6713\include\DSK6713_AIC23.h"
//codec-dsk support file
#include<stdio.h>
Uint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling rate
int x[15],h[15],y[15];
main()
102

{
int i,j,m,n;
printf("\n enter value for m");
Page

scanf("%d",&m);
Digital Signal Processing Lab Manual

printf("\n enter value for n");


scanf("%d",&n);
printf("Enter values for i/p\n");
for(i=0;i<m;i++)
scanf("%d",&x[i]);
printf("Enter Values for n \n");
for(i=0;i<n;i++)
scanf("%d",&h[i]);
for(i=m;i<=m+n-1;i++)
x[i]=0;
for(i=n;i<=m+n-1;i++)
h[i]=0;

for(i=0;i<m+n-1;i++)
{
y[i]=0;
for(j=0;j<=i;j++)
{
y[i]=y[i]+(x[j]*h[i-j]);
}
}

for(i=0;i<m+n-1;i++)
printf("\n The Value of output y[%d]=%d",i,y[i]);
}
6. Add Convolution.C file to the project
7. Compiler Option
Select Project  Build Options. Figure 3 shows the CCS window Build Options for
the compiler.
I. Select the following for the compiler option with Basic (for Category):
a) c671x{-mv6710} (for Target Version),
b) Full Symbolic Debug (for Generate Debug Info),
c) Speed most critical (for Opt Speed vs. Size),
d) None (for Opt Level and Program Level Opt).
II. Select the Preprocessor Category and type for Define Symbols{d}: CHIP_6713
III. Select the Files Category and type for Obj Directory(-fr) D:\Program
files\My Projects\Convolution\Debug
IV. Select the Advanced Category and select for Memory Models Far
103
Page
Digital Signal Processing Lab Manual

Figure-3 CCS Build options: compiler.

8. Linker Option
Click on Linker (from CCS Build Options).
V. Select the following for the compiler option with Basic (for Category):
a) Select Suppress banner
b) Select Exhaustively Read Library
c) For Output Filename (-o) type .\Debug\ Convolution.out
d) For Map Filename (-o) type .\Debug\ Convolution.map
e) For Autoinit Model: Select Run-Time Autoinitialization(-c)
104
Page
Digital Signal Processing Lab Manual

Figure-4 CCS Build options: linker.

9. Building and Running the Project


VI. Select Project  Rebuild All or press the toolbar with the three down arrows .
This creates an executable file BASK.out that can be loaded into the C6713
processor and run. Note that the commands for compiling, assembling, and linking
are performed with the Build option. A log file cc_build_Debug.log is created that
shows the files that are compiled and assembled, along with the compiler options
selected. It also lists the support functions that are used.
Select File  Load Program in order to load BASK.out by clicking on it (CCS includes an
option to load the program automatically after a build). It should be in the folder BASK\Debug.
Select Debug  Run or use the toolbar with the “running man.”
Result:
enter value for m4

enter value for n4


Enter values for i/p
105

1234
Enter Values for n
Page

1234
Digital Signal Processing Lab Manual

The Value of output y[0]=1


The Value of output y[1]=4
The Value of output y[2]=10
The Value of output y[3]=20
The Value of output y[4]=25
The Value of output y[5]=24
The Value of output y[6]=16

106
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 15
Title: Circular Convolution
Equipment Required:
TMS 320C6713 Kit.
RS232 Serial Cable
Power Cord
AIM
To verify Circular Convolution.

THEORY

Circular convolution is another way of finding the convolution sum of two input signals. It
resembles the linear convolution, except that the sample values of one of the input signals is
folded and right shifted before the convolution sum is found. Also note that circular convolution
could also be found by taking the DFT of the two input signals and finding the product of the
two frequency domain signals. The Inverse DFT of the product would give the output of the
signal in the time domain which is the circular convolution output. The two input signals could
have been of varying sample lengths. But we take the DFT of higher point, which ever signals
levels to. For eg. If one of the signal is of length 256 and the other spans 51 samples, then we
could only take 256 point DFT. So the output of IDFT would be containing 256 samples instead
of 306 samples, which follows N1+N2 – 1 where N1 & N2 are the lengths 256 and 51
respectively of the two inputs. Thus the output which should have been 306 samples long is
fitted into 256 samples. The
256 points end up being a distorted version of the correct signal. This process is called circular
convolution.

PROGRAM:

/* prg to implement circular convolution */

#include<stdio.h>
int m,n,x[30],h[30],y[30],i,j,temp[30],k,x2[30],a[30];
107

void main()
{
Page

printf(" enter the length of the first sequence\n");


scanf("%d",&m);
Digital Signal Processing Lab Manual

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++)
y[0]+=x[i]*a[i];
for(k=1;k<n;k++)
{
108

y[k]=0;
/*circular shift*/
Page

for(j=1;j<n;j++)
Digital Signal Processing Lab Manual

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 \t",y[i]);
}

OUTPUT:-

Enter the first sequence


5
6
7
Enter the second sequence
7
8
5
4

OUTPUT ;- the circular convolution is

94 110 122 106

Model Graph:-
109
Page
Digital Signal Processing Lab Manual

110
Page
Digital Signal Processing Lab Manual

University of Engineering & Technology Lahore


Faculty of Engineering
Experiment # 16
Title: CORRELATION
Equipment Required:
TMS 320C6713 Kit.
RS232 Serial Cable
Power Cord
AIM: To convert Circular Convolution

THEORY:
Correlation is measures of the degree to which two sequences are similar .There are two types of
Correlation 1. Cross correlation 2.Auto correlation
Cross Correlation:- given two real valued sequences x1(n) of finite energy , the cross
correlation of x1(n) and x2(n) is a sequence rxy (1) defined as

rxy( 1 )=

#include<stdio.h>
int m,n,X[30],RXY[30],Y[30],i,j,temp[30],k,X2[30],a[30];
void main()
{
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 secound sequence\n");
for(j=0;j<n;j++)
scanf("%d",&Y[j]);
for(i=n;i<m+n-1;i++)
X[i]=0;

for(i=m;i<n+m-1;i++)
Y[i]=0;
111

if(m>n)
a=m;
Page

else
Digital Signal Processing Lab Manual

a=n

for(l=0;l<a;l++)
{
RXY[l]=0;
for(n=0;n<a;n++)

{
RXY[l]+=X[n+l]*X2[n];
}
}
printf("the correlation is\n");
for(i=0;i<n;i++)
printf("%d\t",RXY[i]);
}

enter the length of the first sequence


5
enter the length of the second sequence
5
enter the first sequence
5,5,5,5,5,5
enter the secound sequence
5,5,5,5,5,5
the correlation is
125,100,75,50,25

OUTPUT:

112
Page
Digital Signal Processing Lab Manual

113
Page

Potrebbero piacerti anche