DSPLABMANUL

136
Page 1 Digital Signal Processing Lab Manual University of Central Punjab 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. Prepared by :-ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Transcript of DSPLABMANUL

Page 1: DSPLABMANUL

Page

1

Digital Signal Processing Lab Manual

University of Central Punjab 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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 2: DSPLABMANUL

Page

2

Digital Signal Processing Lab Manual

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.(b) Next try the following:

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Command Window

Workspace Window

Command

History Window

Page 3: DSPLABMANUL

Page

3

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 format command . 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 formatsCommand Description Example

format short Fixed-point with 4 decimal digits for:0.001 ≤ number ≤1000 Otherwise display format short e.

>> format short>> 290/7ans = 41.4286

format long Fixed-point with 14decimal digits. >> format long>> 290/7ans = 41.428571428571431

format short e Scientific notation with 4 decimal digits. >> format short e>> 290/7ans = 4.1429e+001

format long e Scientific notation with 15 decimal digits. >> format long e>> 290/7ans = 4.142857142857143e+001

format short g Best of 5-digit fixed or floating point. >> format short g>> 290/7

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 4: DSPLABMANUL

Page

4

Digital Signal Processing Lab Manual

ans = 41.429format long g Best of I5-digit fixed or floating point. >> format long g

>> 290/7ans = 41.4285714285714

format bank Two decimal digits. >> format bank>> 290/7ans = 41.43

5) ELEMENTARY MATH BUILT-IN FUNCTIONSIn 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 Examplesqrt(x) Square root. >> sqrt(81)

ans = 9.00exp(x) Exponential (ex). >> exp(5)

ans = 148.41abs (x) Absolute value. >> abs (-24)

ans = 24.00log (x) Natural logarithm.

Base e logarithm (In).>> log(1000)ans = 6.91

log10(x) Base 10 logarithm. >> log10(1000)ans = 3.00

factorial (x) The factorial function x!(x must be a positive integer.)

>> factorial (5)ans = 120.00

Function Description Examplesin(x) Sine of angle x (x in

radians).>> sin(pi/6)ans = 0.5000

cos(x) Cosine of angle x (x in radians).

>> cos(pi/6)ans = 0.8660

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 5: DSPLABMANUL

Page

5

Digital Signal Processing Lab Manual

tan (x) Tangent of angle x (x in radians).

>> tan(pi/6)ans = 0.5774

cot (x) Cotangent of angle x (.x in radians).

>> cot(pi/6)ans = 1.7321

Rounding functionsFunction Description Exampleround (x) Round to the nearest

integer.>> round (17/5)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 infinity.

>> floor(-9/4)ans = -3

rem(x,y) Returns the remainder after x is divided by y.

>> rem(13,5)ans = 3

sign(x) Signum function. Returns 1 ifx > 0 , -1 if x < 0, and 0 if x = 0

>> sign(5)ans = 1

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:

a)

35 .7∗64−73

45+52

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 6: DSPLABMANUL

Page

6

Digital Signal Processing Lab Manual

b)

54∗7∗62+ 37

( 93−652)

c)(2+7 )3+2732/3

2+552

3

d)23+73+2733

2+553/2

e)37 log (76 )

73+546+3√910

f)43∗

4√250+23

e(45−33)

g)cos2( 5 π

6 )sin( 7 π8 )

2

+tan( π

6ln 8)

√7

h)

cos( 5π6 )

2

sin2( 7 π8 )+

tan( π ln 86 )

7∗52

2) Define the variable x as x = 13.5, then evaluate:

a) x3+5 x2−26 .7 x−52

b)√14 x3

e3 x

c) log|x2−x3|3) Define the variable x and z as x = 9.6, and z=8.1, then evaluate

a)xz2−( 2 z

3 x )35

b)443 z2 x3

+ e− xz

( 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:

a)a+ ab

c∗

(a+d )2

√|ab|

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 7: DSPLABMANUL

Page

7

Digital Signal Processing Lab Manual

b)de

( d2 )

+

ad+cd20a

+30b

a+b+c+d

University of Central Punjab 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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 8: DSPLABMANUL

Page

8

Digital Signal Processing Lab Manual

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. Type the right square bracket]

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

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 13x =

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 9: DSPLABMANUL

Page

9

Digital Signal Processing Lab Manual

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

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)va = 0 1.6000 3.2000 4.8000 6.4000 8.0000>> va = linspace(30,10,11)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 21 32 40>> a = [5 35 434 76 8121 32 40]a = 5 35 43

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

6 elements, first element 0, last element8

11 elements, first element 30, last element10

A semicolon is typed before a new line is entered.

A Enter key is pressed before a new line is entered.

Page 10: DSPLABMANUL

Page

10

Digital Signal Processing Lab Manual

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.Example:>> 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 CommandsThe 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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 11: DSPLABMANUL

Page

11

Digital Signal Processing Lab Manual

6) The Transpose Operator:-The transpose operator is applied by typing a single quote' following the variable to

be transposed.

Examples:>> 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 AddressingElements 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 2351481355thenve(4) = 23, ve(7) = 81, and ve(1) = 35.Example:->> VCT = [35 46 78 23 5 14 81 3 55]VCT = 35 46 78 23 5 14 81 3 55>> VCT(4)ans =

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Define a Vector

Display the fourth element

Page 12: DSPLABMANUL

Page

12

Digital Signal Processing Lab Manual

23>> VCT(6)=273VCT = 35 46 78 23 5 273 81 3 55>> VCT(2)+VCT(8)ans = 49>> VCT(5)^VCT(8)+sqrt(VCT(7))ans = 1347.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:

ma=[ 3413

1179

6100

528 ]

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 usedLike variables in mathematical expressions and functions. Examples:>> 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)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)=20MAT = 3 11 6 5

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Assign a new value to the sixth element

The whole vector is displayed

Use the vector elements in mathematical expressions

Create a 3 X 4 matrix

Assign a new value to the (3,1) element.

Page 13: DSPLABMANUL

Page

13

Digital Signal Processing Lab Manual

4 7 10 2 20 9 0 8>> MAT(2,4)-MAT(1,2)ans = -97.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]v = 4 15 8 12 34 2 50 23 11>> u = v(3:7)u = 8 12 34 2 50

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 3 6 9 12 15 18>> B = A(:,3)B = 5 6 9>> C = A(2,:)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Use the elements in a mathematical expression

A vector v is created

A vector u is created from the elements 3 through 7 of vector v.

Define a matrix A with 3 rows and 6 columns.

Define a column vector B from the elements in all the rows of column 3 in matrix A.

Define a row vector C from the elements in all the columns of row 2 in matrix A.

Page 14: DSPLABMANUL

Page

14

Digital Signal Processing Lab Manual

C = 2 4 6 8 10 12>> E = A(1:3,:)E = 1 3 5 7 9 11 2 4 6 8 10 12 3 6 9 12 15 18>> F = A(1:3,2:4)F = 3 5 7 4 6 8 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:34v = 4 7 10 13 16 19 22 25 28 31 34>> u = v([3,5,7:10])u = 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 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])B = 10 8 6 5 4 2 6 10 12 14

8) Adding Elements to Existing VariablesA 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 elementsExample:- >> DF = 1:4DF =

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Define a column matrix E from the elements in the rows 1 through 3 and all the columns in matrix A.

Define a column matrix F from the elements in the rows 1 through 3 and the columns 2 through 4 in matrix A.

Create a vector v with 11 elements.

Create a vector u from the 3rd, the 5th , and 7th through 10th elements of v

Create a 4 X 7 matrix A.

Create a matrix B from the 1st and 3rd rows and 1st,3rd , and 5th through 7th columns of A.

Define vector DF with 4 elements

Page 15: DSPLABMANUL

Page

15

Digital Signal Processing Lab Manual

1 2 3 4>> DF(5:10)=10:5:35DF = 1 2 3 4 10 15 20 25 30 35>> AD = [5 7 2]AD = 5 7 2>> AD(8)=4AD = 5 7 2 0 0 0 0 4>> AR(5)=24AR = 0 0 0 0 248.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]E = 1 2 3 4 5 6 7 8>> E(3,:)=[10:4:22]E = 1 2 3 4 5 6 7 8 10 14 18 22>> K = eye(3)K = 1 0 0 0 1 0 0 0 1>> G = [E K]G = 1 2 3 4 1 0 0 5 6 7 8 0 1 0 10 14 18 22 0 0 1

9) Built-in Functions for Handling Arrays:-

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Adding 6 elements starting with the 5th.

Define vector AD with 3 elements

Assign a value to the 8th element.

MATLAB assignd zeros to the 4th through 7th elements,

Define a 2X4 matrix E.

Adding the vector 10 14 18 22 as the third row of E.

Define a 3X3 matrix K.

Append the matrix K to matrix E. the number of rows in E and K must be the same.

Page 16: DSPLABMANUL

Page

16

Digital Signal Processing Lab Manual

MATLAB has many built-in functions for managing and handling arrays. Some of these are listed below:

Built-in functions for handling arraysFunction Description Examplelength (A) Returns the number of elements in

the vector A.>> A = [5 9 2 4];>> length(A)ans = 4

size(A) Returns a row vector [m, n] , where m and n are the size m X n of the array A.

>> A = [6 1 4 0 12; 5 19 6 8 2];>> size(A)ans = 2 5

reshape(A,m,n) Rearrange a matrix A that has r rows and s columns to have m rows and n columns. r times s must be equal to m times n.

>> A = [5 1 6; 8 0 2]A = 5 1 6 8 0 2>> B = reshape(A,3,2)B = 5 0 8 6 1 2

diag(v) When v is a vector, creates a square matrix with the elements of v in the diagonal.

>> v = [7 4 2]v = 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 vector from the diagonal elements of A.

>> A = [1 2 3; 4 5 6; 7 8 9]A = 1 2 3 4 5 6 7 8 9>> vec = diag(A)vec = 1

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 17: DSPLABMANUL

Page

17

Digital Signal Processing Lab Manual

5 9

Assignment 5:-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.

B=[ 1720

4660 .125

760 0 .250

1054 0 .375

1348 0 .500

16 42 0 . 625

1936 0 . 750

2230 0 .875

2524 1 .000]

Assignment 8:-

Create the following matrix A:

A=[ 612 34

43 6 18

2 34 7

11 0 41

875

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:

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 18: DSPLABMANUL

Page

18

Digital Signal Processing Lab Manual

A=[23746

14

69

21

812 28

1015 35]

Use the matrix C to:a) Create a three-element column vector named ua that contains the elements of the third column of C.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:

A=[ I2

215

24

1810

36

1515

48

1220

5109

25

6126

30

7143

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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 19: DSPLABMANUL

Page

19

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 3

Title: Two Dimensional Plots.

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

1) The plot Command:-

The plot command is used to create two-dimensional plots. The simplest form of the command is:

plot(x,y)

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:

1.1) Line Specifiers:-

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Vector Vector

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

Vector Vector (Optional) Specifiers that define the type and color of the line and markers.

(Optional) Properties with values that can be used to specify the line width, and marker's size and edge, and fill colors.

Page 20: DSPLABMANUL

Page

20

Digital Signal Processing Lab Manual

The line style specifiers are:Line Style Specifiersolid (default) -Dashed --Dotted :dash-dot -.

The line color specifiers are:

Line Color Specifier Line Color Specifierred r magenta m green g yellow yblue b black kcyan c white w

The marker type specifiers are:Marker Type Specifier Marker Type Specifierplus sign + square scircle o diamond dasterisk * five-pointed star ppoint . 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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

LEGEND

Page 21: DSPLABMANUL

Page

21

Digital Signal Processing Lab Manual

8 10 12 14 16 18 20 22 240

200

400

600

800

1000

1200

DISTANCE (cm)

INT

EN

SIT

Y (

lux)

light Intensity as a Function of Distance

Comparison between theory and experiment

Theory

Experiment

2) THE fplot COMMANDThe fplot command plots a function with the form y = f(x) between specified limits. The

command has the form:

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 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].

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

fplot('function' ,limits,line specifiers)

The function to be plotted.

The domain of x, and optionally, the limits of the y axis.

Specifiers that define the type and color of the line and markers (optional).

PLOT

TEXT LABEL

X AXIS LABEL

Y AXIS LABEL

MARKER

Page 22: DSPLABMANUL

Page

22

Digital Signal Processing Lab Manual

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 dotted green line.

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)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

(Optional) Properties with values that can be used to specify the line style, color, and width, marker type, size, and edge and fill colors.

Page 23: DSPLABMANUL

Page

23

Digital Signal Processing Lab Manual

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:

title ('text as string')

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

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 )

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 24: DSPLABMANUL

Page

24

Digital Signal Processing Lab Manual

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 numbers increase from left to right within a row, from the first row to the last. The command subplot(m, n, p) makes the subplot P current.

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 1994SALES

(millions)8 12 20 22 18 24 27

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 25: DSPLABMANUL

Page

25

Digital Signal Processing Lab Manual

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)

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];

y = x.^2+4.*sin(2.*x)-1;

plot(x,y)

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.SolutionThe 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];

y =3*x.^3 -26*x+ 6;

yd = 9*x.^2-26;

ydd =18*x;

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Line Specifiers: dashed red line and asterisk marker.

Property Name and Property Value: the line width is 2 points and the markers size is 12 point.

Create vector x with the domain of the function.

Create vector y with the function value at each x.

Plot y as a function of x.

Create vector x with the domain of the function.

Create vector y with the function value at each x.

Create vector yd with values of the first derivative.

Create vector ydd with values of the second derivative.

Page 26: DSPLABMANUL

Page

26

Digital Signal Processing Lab Manual

plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

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')

hold on

plot(x,yd,'--r')

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;

xd =[10:2:22];

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

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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Create three graphs, y vs. x, yd vs x and ydd vs. x in the same figure.

The first graph is created.

Two more graphs are added to the figure

Page 27: DSPLABMANUL

Page

27

Digital Signal Processing Lab Manual

1) Make two separate plots of the function f ( x )=0 .6 x5−5 x3+9x+2

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

2) Plot the function f ( x )= x2−x+1

x2+x+1 for -10 ≤ x ≤ 10

3) Use the fplot command to plot the function:

f ( x )=0 . 01 x5−0 .03 x4+0 . 4 x3−2 x2−6 x+5

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.

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”.

University of Central Punjab Faculty of Engineering

Experiment # 4

Title: Functions and Function Files.

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

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 28: DSPLABMANUL

Page

28

Digital Signal Processing Lab Manual

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.

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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

function [output arguments] = function_name (input arguments)

The word function must be the first word, and must be typed in lower-case letters.

A list of output arguments typed inside brackets.

The name of the function.

A list of input arguments typed inside parentheses.

Function definition line

The H1 line

Help text

Function body (Computer program).

Assignment values to output arguments.

Page 29: DSPLABMANUL

Page

29

Digital Signal Processing Lab Manual

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 are separated with commas. The following are example of function definition lines with different combinations of input and output arguments.

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 30: DSPLABMANUL

Page

30

Digital Signal Processing Lab Manual

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:

Procedure:-

Execute the following example in MATLAB

1) The function:-

Example:-

Write a function file for the function f ( x )= x4√3 x+5

(x2+1)2 the input to the function is x

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)y= (x.^4.*sqrt(3*x+5))./(x.^2+1).^2;

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

>> exp4one(6)ans = 4.5401

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

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

Function definition line

Assignment to output argument.

Page 31: DSPLABMANUL

Page

31

Digital Signal Processing Lab Manual

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:11x = 1 3 5 7 9 11>> exp4one(x)ans = 0.7071 3.0307 4.1347 4.8971 5.5197 6.0638

The inline Function:-

The function f ( x )= ex2

√x2 +5 can be defined (in the Command Window) as an inline 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:

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 32: DSPLABMANUL

Page

32

Digital Signal Processing Lab Manual

>> HA(2,3)ans = -7

Assignment :- Converting temperature unitsWrite 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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 33: DSPLABMANUL

Page

33

Digital Signal Processing Lab Manual

University of Central Punjab 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]

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 34: DSPLABMANUL

Page

34

Digital Signal Processing Lab Manual

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:

δ (n )=¿ {1 , n=0 ¿ ¿¿¿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

δ (n−no )=¿ {1 , n=no ¿¿¿¿

over then1≤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 sequencestem(n,u);xlabel(‘time index n’);ylabel(‘Amplitude’);title(‘Unit Sample Sequence’);axis([-10 20 0 1.2]);

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 35: DSPLABMANUL

Page

35

Digital Signal Processing Lab Manual

Task 1:Generate and plot the sequence

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

MATLAB CODE:-

2. Unit step sequence:

u(n )=¿ {1 , 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

u(n−no )=¿ {1 , n≥no ¿ ¿¿¿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 sequencestem(n,x);

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 36: DSPLABMANUL

Page

36

Digital Signal Processing Lab Manual

xlabel('time index n');ylabel('Amplitude');title('Unit Step Sequence');axis([-20 10 0 1.2]);

Task 2:Generate and plot the sequence

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

MATLAB CODE:-

3. Real-valued exponential sequence:-

x (n )=an ,∀n ; a∈ℜIn MATLAB an array operator “.^” is, required to implement a real exponential sequence. Example:-

Generate x (n )=(0 . 9 )n0≤n≤10 ,

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 37: DSPLABMANUL

Page

37

Digital Signal Processing Lab Manual

Task 3:Generate and plot the sequence

x (n )=(−10 )n −10≤n≤10MATLAB CODE:-

4. Complex-valued exponential sequence :

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.Ex ample:-

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:

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 38: DSPLABMANUL

Page

38

Digital Signal Processing Lab Manual

x (n )=cos (won+θ ) ,∀n

where θ is the phase in radians. A MATLAB function cos (or sin) is used to generate sinusoidal sequences. Example, Generatex (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);

EXAMPLE 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

b. x (n )=n[ u(n )−u(n−10 )]+10 e−. 03 (n−10) [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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 39: DSPLABMANUL

Page

39

Digital Signal Processing Lab Manual

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

-0.5

0

0.5

1

1.5

2Sequence in example a

n

x(n)

0 2 4 6 8 10 12 14 16 18 200

2

4

6

8

10Sequence in example b

n

x (n

)

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 40: DSPLABMANUL

Page

40

Digital Signal Processing Lab Manual

5.

University of Central Punjab Faculty of Engineering

Experiment # 6

Title: OPERATIONS ON SEQUENCES

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

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)} + { x2( n)} = {x1( n) + x2 (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 FUNCTIONfunction [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)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 41: DSPLABMANUL

Page

41

Digital Signal Processing Lab Manual

%n = min(min(n1),min(n2)) :max(max(n1) ,max(n2));%duration of y(n)y1= zeros(1,length(n)); y2 = y1; %initializationy1(find((n>=min(n1))&(n<=max(n1))==1))=x1; %x1 with duration of yy2(find((n>=min(n2))&(n<=max(n2))==1))=x2; %x2 with duration of yy = y1+y2; %sequence Addition

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 FUNCTIONfunction [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 yy = 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 byy (m + k) = {x (m)}

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 42: DSPLABMANUL

Page

42

Digital Signal Processing Lab Manual

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.

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

5- F olding: 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 FUNCTIONfunction [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

∑n=n1

n 2

x (n)=x (n1)+. .. . .. .. . ..+x (n2 )

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 43: DSPLABMANUL

Page

43

Digital Signal Processing Lab Manual

∏n=n1

n 2

x (n)=x (n1)×.. .. . .. .. . .×x (n2 ).

It is implemented by the prod (x (n1 : n2)) function.8- Signal energy:

The energy of a sequence x(n) is given by

ε x=∑−∞

x (n) x¿(n )=∑−∞

|x( n)|2

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

Ρx=1N

∑0

N−1

|x( n)|2

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. x2(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];

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 44: DSPLABMANUL

Page

44

Digital Signal Processing Lab Manual

will generate x(n).

a. x1(n )= 2x (n - 5 ) - 3x ( n + 4 )

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. x2(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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 45: DSPLABMANUL

Page

45

Digital Signal Processing Lab Manual

-10 -5 0 5 10 15-30

-20

-10

0

10

20Sequence in Examplea

n

x1(n

)

-8 -6 -4 -2 0 2 4 6 8 10 120

10

20

30

40Sequence in Exampleb

n

x2 (

n)

Assignment Letx(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. x2(n )= 5x (5+n )+4 x (n+4 )+3x(n )

c. x3(n )= x (n+4 )x (n-1 )+x (2-n ) x(n )

d. x4 (n )= 2e0 .5n x (n )+cos(0 .1 πn )x (n+2 ) , -10≤n≤10

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 46: DSPLABMANUL

Page

46

Digital Signal Processing Lab Manual

e. x5(n )=∑

k=1

5

nx (n-k )

University of Central Punjab Faculty of Engineering

Experiment # 7

Title: The Discrete-time Fourier Transform (DTFT)

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

If x(n) is absolutely summable, that is, ∑n=−∞

∞|x (n )|<∞ , then its discrete- time

Fourier Transform is given by

X ( e jw )=F [ x (n ) ]= ∑n=−∞

x (n )e− 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

X(ejw) 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 π|)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 47: DSPLABMANUL

Page

47

Digital Signal Processing Lab Manual

Implication: We need only one period of X(ejw) (i.e. ω∈[ 0,2 π ] , or [−π , π ] , etc.) for analysis and not the whole domain−∞∈ω∈∞ .

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≈πM

k , k=0,1 ,. . .. .. . .. , M

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

X ( ejωk)=∑

l=1

N

e− j (π /M )knl x (nl) , k=0,1,. . .. .. . ,M

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 48: DSPLABMANUL

Page

48

Digital Signal Processing Lab Manual

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

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

W =[exp (− jπM

kT n)]In MATLAB we represent sequences and indices as row vectors; therefore taking the transpose of (3),

XT=xT [exp(− jπM

knT)] …….(4)

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.

X ( e jw )= ∑n=−∞

x (n )e− jwn=∑n=0

(0 .5)n e− jwn

=∑n=0

∞(0 . 5 e− jw )n= 1

1−0 .5 e− jw= e jw

e jw−0 . 5

MATLABScriptw = [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);

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 49: DSPLABMANUL

Page

49

Digital Signal Processing Lab Manual

subplot(2,2,1); plot(w/pi,magX); gridxlabel('frequency in pi units'); title('Magnitude Part');ylabel('Magnitude')subplot(2,2,3); plot(w/pi,angX); gridxlabel('frequency in pi units');title('AnglePart');ylabel('Radians')subplot(2,2,2);plot(w/pi,realX);gridxlabel('frequency in pi units'); title('Real Part'); ylabel('Real')subplot(2,2,4); plot(w/pi,imagX); gridxlabel('frequency in pi units'); title('Imaginary Part'); ylabel('Imaginary')

0 0.2 0.4 0.6 0.8 10.5

1

1.5

2

frequency in pi units

Magnitude Part

Mag

nitu

de

0 0.2 0.4 0.6 0.8 1-0.8

-0.6

-0.4

-0.2

0

frequency in pi units

AnglePart

Rad

ians

0 0.2 0.4 0.6 0.8 10.5

1

1.5

2

frequency in pi units

Real Part

Rea

l

0 0.2 0.4 0.6 0.8 1-0.8

-0.6

-0.4

-0.2

0

frequency in pi units

Imaginary Part

Imag

inar

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 50: DSPLABMANUL

Page

50

Digital Signal Processing Lab Manual

n = -1:3; x = 1:5; %sequence x(n)k = 0:500; w =(pi/500)*k;%[0,pi]axis divided into 501pointsX = x * (exp(-j*pi/500)) .^ (n'*k);magX = abs(X); angX = angle(X);realX = real(X); imagX = imag(X);subplot(2,2,1); plot(k/500,magX);gridxlabel('frequency in pi units'); title('Magnitude Part')subplot(2,2,3); plot(k/500,angX/pi);gridxlabel('frequency in pi units'); title('Angle Part')subplot(2,2,2); plot(k/500,realX);gridxlabel ( 'frequency in pi units'); title ('Real Part')subplot(2,2,4); plot(k/500,imagX);gridxlabel('frequency in pi units'); title('Imaginary part')

0 0.2 0.4 0.6 0.8 10

5

10

15

frequency in pi units

Magnitude Part

0 0.2 0.4 0.6 0.8 1-1

-0.5

0

0.5

1

frequency in pi units

Angle Part

0 0.2 0.4 0.6 0.8 1-5

0

5

10

15

frequency in pi units

Real Part

0 0.2 0.4 0.6 0.8 1-10

-5

0

5

frequency in pi units

Imaginary part

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

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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Solution

Page 51: DSPLABMANUL

Page

51

Digital Signal Processing Lab Manual

MATLABScriptn = 0:10; x = (0.9*exp(j*pi/3)).^n;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);gridxlabel('frequency in units of pi'); ylabel('|X|')axis([-2,2,0,8])title('Magnitude Part')subplot(2,1,2); plot(w/pi,angX/pi);gridxlabel('frequency in units of pi'); ylabel('radians/pi')axis([-2,2,-.5,.5])title('Angle Part')

-2 -1.5 -1 -0.5 0 0.5 1 1.5 20

2

4

6

8

frequency in units of pi

|X|

Magnitude Part

-2 -1.5 -1 -0.5 0 0.5 1 1.5 2-0.5

0

0.5

frequency in units of pi

radi

ans/

pi

Angle Part

4) Example:-Let x(n)= (-0.9)n, -10 ≤n ≤ 10. Investigate the conjugate-symmetry property of its discrete-time Fourier transform.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Solution

Page 52: DSPLABMANUL

Page

52

Digital Signal Processing Lab Manual

Once again we will compute and plot X(ejw) over two periods to study its symmetry property.

MATLABScriptn = -5:5; x = (-0.9).^n;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);gridaxis([-2,2,0,15])xlabel('frequency in units of pi'); ylabel('|X|')title('Magnitude Part')subplot(2,1,2); plot(w/pi,angX/pi);gridaxis([-2,2,-1,1])xlabel('frequency in units of pi'); ylabel('radians/pi')title('Angle Part')

-2 -1.5 -1 -0.5 0 0.5 1 1.5 20

5

10

15

frequency in units of pi

|X|

Magnitude Part

-2 -1.5 -1 -0.5 0 0.5 1 1.5 2-1

-0.5

0

0.5

1

frequency in units of pi

radi

ans/

pi

Angle Part

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 53: DSPLABMANUL

Page

53

Digital Signal Processing Lab Manual

ProblemsFor 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}

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 54: DSPLABMANUL

Page

54

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 8

Title: Properties of DTFTEquipment Required: Personal computer (PC) with windows operating system and MATLAB softwareTheory:-

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 )ejwo n

]=X (ej (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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 55: DSPLABMANUL

Page

55

Digital Signal Processing Lab Manual

F [ x (−n) ]=X (e− jw )

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 Filexl = 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 x1X2 = x2 * (exp(-j*pi/500)).^(n'*k); %DTFT of x2x = alpha*xl + beta*x2; %Linear combinationof x1&x2X = x * (exp(-j*pi/500)).^(n'*k); % DTFT of x % verificationX_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 Filex = rand(1,11); n = 0:10;k = 0:500; w = (pi/500)*k;

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 56: DSPLABMANUL

Page

56

Digital Signal Processing Lab Manual

X = x * (exp(-j*pi/500)).^(n'*k); % DTFT of x% signal shifted by two samples y = x; m = n+2;Y = y* (exp(-j*pi/500)).^(m'*k); % DTFT of Y% verificationY_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

x (n )=cos (πn /2 ) , 0≤n≤100 and y (n )=e jπn/4 x (n)Then using MATLAB,

MATLAB Script Filen = 0:100; x = cos(pi*n/2);k = -100:100; w = (pi/100)*k; %frequency between -pi and +piX = 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 verificationsubplot(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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 57: DSPLABMANUL

Page

57

Digital Signal Processing Lab Manual

-1 -0.5 0 0.5 10

20

40

60

frequency in pi units

|X|

Magnitude of X

-1 -0.5 0 0.5 1-1

-0.5

0

0.5

1

frequency in pi units

radi

ands

/pi

Angle of X

-1 -0.5 0 0.5 10

20

40

60

frequency in pi units

|Y|

Magnitude of Y

-1 -0.5 0 0.5 1-1

-0.5

0

0.5

1

frequency in pi units

radi

ans/

pi

Angle of Y

Figure#1 Frequency shifting property

4) Verifying the Conjugation propertyTo 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 Filen = -5:10; x = rand(1,length(n)) + j*rand(1,length(n));k = -100:100; w = (pi/100)*k; %frequency between -pi and +piX = x * (exp(-j*pi/100)).^(n'*k);% DTFT of x %conjugation propertyy = conj(x); % signal conjugationY =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

5) Verifying the Folding property

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 58: DSPLABMANUL

Page

58

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 Filen = -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 propertyy = fliplr(x); m = -fliplr(n); % Signal folding Y = y * (exp(-j*pi/100)).^(m'*k);% DTFT of Y% verificationY_check = fliplr(X); % X(-w)error = max(abs(Y-Y_check)) % Difference

MATLAB Output:

6) Verifying the Symmetries in real sequences propertyTo verify the symmetry property (6) of real signals, Let

x (n )=sin(nπ /2) , -5 ≤ n ≤ 10Then 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 Filen = -5:10; x = sin(pi*n/2);k=-100:100; w=(pi/100)*k; % frequency between -pi and +piX = x * (exp(-j*pi/100)).^(n'*k); % DTFT of x% signal decomposition[xe,xo,m] = evenodd(x,n); % even and odd partsXE = xe * (exp(-j*pi/100)).^(m'*k); % DTFT of xeXO = xo * (exp(-j*pi/100)).^(m'*k); % DTFT of xo% verificationXR = real(X); % real part of Xerrorl = max(abs(XE-XR)) % DifferenceXI = imag(X); % imag part of Xerror2 = max(abs(XO-j*XI)) % Difference% graphical verificationsubplot(1,1,1)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 59: DSPLABMANUL

Page

59

Digital Signal Processing Lab Manual

subplot(2,2,1); plot(w/pi,XR); grid; axis([-1,1,-2,2])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:

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 60: DSPLABMANUL

Page

60

Digital Signal Processing Lab Manual

-1 -0.5 0 0.5 1-2

-1

0

1

2

frequency in pi units

Re(

X)

Real part of X

-1 -0.5 0 0.5 1-10

-5

0

5

10

frequency in pi units

Im(X

)

Imaginary part of X

-1 -0.5 0 0.5 1-2

-1

0

1

2

frequency in pi units

XE

Transform of even part

-1 -0.5 0 0.5 1-10

-5

0

5

10

frequency in pi units

XO

Transform of odd part

University of Central Punjab 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:

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 61: DSPLABMANUL

Page

61

Digital Signal Processing Lab Manual

(DTFT):X ( e jω)= ∑

n=−∞

x (n )e− jωn

(1)

(IDTFT):x (n )= 1

2 π∫−π

π

X (e jω)e jωn

(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

Analysis Equation (DFT):X ( k )=∑

n=0

N −1

x (n)e− j 2 π kn / N

(3)

Synthesis Equation (lDFT):x (n )= 1

N∑k=0

N −1

X ( k )e j 2 π kn /N

(4)

Where X(k) is an N-point DFT of x[n]. Note that X(k)is a function of a discrete integer k, where k ranges from 0 to N-1.

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

W Nnk=e− j 2 π kn /N

Equation (3) and (4) can be written as: X ( k )=∑

n=0

N −1

x (n)W Nnk

(6)

Analysis Equation (DFT):x (n )= 1

N∑k=0

N −1

X ( k )W Nnk

(7)

Or equivalently,

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 62: DSPLABMANUL

Page

62

Digital Signal Processing Lab Manual

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)%ComputeDiscreteFourierTransformn=[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 Transformn= [0:1:N-1];k = [0:1:N-1];WN = exp (-j * 2 * pi / N);nk = n' * k;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:-

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 63: DSPLABMANUL

Page

63

Digital Signal Processing Lab Manual

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])

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 64: DSPLABMANUL

Page

64

Digital Signal Processing Lab Manual

0 10 20 30 40 50 60 70 80 90 100

-2

-1

0

1

2

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

n

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

10

20

30

40

50

60DTFT Magnitude

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;

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 65: DSPLABMANUL

Page

65

Digital Signal Processing Lab Manual

0 10 20 30 40 50 60 70 80 90 100

-2

-1

0

1

2

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

n

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

10

20

30

40

50

60DTFT Magnitude

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])

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 66: DSPLABMANUL

Page

66

Digital Signal Processing Lab Manual

0 5 10 15 20 25 30 35 40 45 50

-2

-1

0

1

2

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

n

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

2

4

6

8

10DTFT Magnitude

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])

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 67: DSPLABMANUL

Page

67

Digital Signal Processing Lab Manual

0 10 20 30 40 50 60 70 80 90 100

-2

-1

0

1

2

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

n

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10

2

4

6

8

10DTFT Magnitude

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=4b. x2(n) = {0,0, 1,0, 0}, N = 5c. X3(n) = {3, -3,3, -3}, N = 4d. x4(n) = {j,j, -j, -j}, N = 4e. 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 = 4b. X2(k)={4,-5,3,-5},N=4c. X3(k)={I,2,3,4,5},N=5d. X4(k)={0,0,2,0},N=4e. X5 (k) = {0,j, -2j, -j}, N = 4

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 68: DSPLABMANUL

Page

68

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 10

Title: Amplitude Modulation (AM)Equipment Required: Personal computer (PC) with windows operating system and MATLAB softwareObjective:

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 follows( t )=Ac[ 1+ka 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 am( t ) is always less than unity; that is,

|ka 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 |ka m( t )|>1 for any t, the carrier wave become over modulated, resulting in carrier

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 69: DSPLABMANUL

Page

69

Digital Signal Processing Lab Manual

phase reversals whenever the factor 1+k am( t ) crosses zero. The modulated wave then exhibits envelope distortion, as in Fig. 1(c).

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 70: DSPLABMANUL

Page

70

Digital Signal Processing Lab Manual

Fig.1. illustration of the amplitude modulation process. (a) message signal m(t).

(b) Am wave for |ka m( t )|<1 for all t (c). AM wave for |ka m( t )|>1 for some t

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 |ka m( t )|<1

|ka 1000|<1

|ka|<1

1000 , ka should be less then .001The 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).

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 71: DSPLABMANUL

Page

71

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 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 fileUint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling ratefloat amp = .0001;short baseband[200]; //index for modulationshort 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,

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 72: DSPLABMANUL

Page

72

Digital Signal Processing Lab Manual

1000,951,809,587,309,0,-309,-587,-809,-951,-1000,-951,-809,-587,-309,0,309,587,809,951};//400-Hz basebandshort 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,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, 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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 73: DSPLABMANUL

Page

73

Digital Signal Processing Lab Manual

7. Linker OptionClick 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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 74: DSPLABMANUL

Page

74

Digital Signal Processing Lab Manual

8. Building and Running the ProjectI. 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 CCSSelect View GraphTime/Frequency.

I. Carrier wave plots Time-domain plot

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 75: DSPLABMANUL

Page

75

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 plotFigure 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)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 76: DSPLABMANUL

Page

76

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 77: DSPLABMANUL

Page

77

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 plotChoose a fast Fourier transform (FFT) order so that the frame size is 2order. 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 plotsReference:

(1) Introduction to Analog and Digital Communication (Simon Haykin, Michael Moher)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 78: DSPLABMANUL

Page

78

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 11

Title: Discrete Fourier Transform (DFT)Equipment Required: Personal computer (PC) with windows operating system and MATLAB softwareObjective: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

X ( k )=DFT {x (n)}=∑n=0

N−1

x (n )e−2 π nk / N k = 0,1,2, .. . .. .. . ..N-1 ……………(1)

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

Let

e− j2 π kn / N=12

( e− j2 π kn /N+e− j2 π kn /N )

¿12

(e− j2 π kn / N+e− j 2 π kn / N+e j 2 π nk / N−e j2 π kn /N )

¿12

(e+ j 2 π kn /N+e− j 2π kn /N )−12

(e j2 π kn / N−e− j2 π kn /N )

where

cos(w )=12

(e jw+e− jw ) and sin( w )=12 j

(e jw−e− jw )⇒ j sin( w)=12

(e jw−e− jw )

e− j2 π kn / N=cos(2 π kn / N )− j sin(2 π kn /N )Eq (1) can be re written as:

X ( k )=DFT {x (n)}=∑n=0

N−1

x (n )( cos(2 π kn/ N )− j sin(2 π kn/ N )) k = 0,1,2,. . .. .. . .. .N-1

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 79: DSPLABMANUL

Page

79

Digital Signal Processing Lab Manual

Or

Re {X (k )}=∑n=0

N −1

x (n)cos (2 π kn /N )

And

Im {X (k )}=∑n=0

N−1

x (n )sin (2 π nk / N )

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.

Discrete Fourier Transform program (DFT.c).

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 80: DSPLABMANUL

Page

80

Digital Signal Processing Lab Manual

______________________________________________________________________________//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 valuesfloat 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 resultsfloat 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

} }} _______________________________________________________________________________________________________________

FIGURE 2. DFT implementation program with input from a lookup table (DFT.c).

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 81: DSPLABMANUL

Page

81

Digital Signal Processing Lab Manual

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_6713III. 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 OptionClick on Linker (from CCS Build Options).

I. Select the following for the compiler option with Basic (for Category): a) Select Suppress bannerb) Select Exhaustively Read Library c) For Output Filename (-o) type .\Debug\DFT.out

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 82: DSPLABMANUL

Page

82

Digital Signal Processing Lab Manual

d) For Map Filename (-o) type .\Debug\DFT.mape) For Autoinit Model: Select Run-Time Autoinitialization(-c)f) For include Libraries type rts6700.lib

II. Click on the Advanced optionsa) De-select Warn About Output Sections(-w)

Figure-4 CCS Build options: linker.

7. Building and Running the ProjectI. 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.

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 the folder DFT\Debug. Select Debug Run or use the toolbar with the “running man.”

8. Monitoring the Watch Window

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 83: DSPLABMANUL

Page

83

Digital Signal Processing Lab Manual

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.

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 84: DSPLABMANUL

Page

84

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 85: DSPLABMANUL

Page

85

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)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 86: DSPLABMANUL

Page

86

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 12

Title: Binary Phase Shift KeyingEquipment Required: Personal computer (PC) with windows operating system and MATLAB softwareDefinition:

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

s( t )=¿ {A cos (2 πf c t )¿ ¿¿¿(1)

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

sd ( t )=A×d (t )×cos (2 πf c t ) (2)

Figure 1 BPSK Modulator

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 87: DSPLABMANUL

Page

87

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 program in it and save it in the folder Myproject\BPSK with name BPSK.C

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 88: DSPLABMANUL

Page

88

Digital Signal Processing Lab Manual

Binary Phase Shift Keying program (BPSK.c).______________________________________________________________________________#include "C:\CCStudio_v3.1\C6000\dsk6713\include\DSK6713_AIC23.h"

//codec-dsk support fileUint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling rateshort 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 -1for(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.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),

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 89: DSPLABMANUL

Page

89

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_6713III. Select the Files Category and type for Obj Directory(-fr) D:\Program

files\My Projects\BPSK\DebugIV. Select the Advanced Category and select for Memory Models Far

Figure-3 CCS Build options: compiler.

7. Linker OptionClick on Linker (from CCS Build Options).

I. Select the following for the compiler option with Basic (for Category): a) Select Suppress bannerb) Select Exhaustively Read Library c) For Output Filename (-o) type .\Debug\BPSK.outd) For Map Filename (-o) type .\Debug\BPSK.mape) For Autoinit Model: Select Run-Time Autoinitialization(-c)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 90: DSPLABMANUL

Page

90

Digital Signal Processing Lab Manual

Figure-4 CCS Build options: linker .

8. Building and Running the ProjectI. 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 CCSSelect View GraphTime/Frequency.

IV. BPSK Signal plot Time-domain plot

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 address of the output buffer is bpsk_signal. The other options can be left as

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 91: DSPLABMANUL

Page

91

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 92: DSPLABMANUL

Page

92

Digital Signal Processing Lab Manual

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

10. Monitoring the Watch WindowSelect 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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 93: DSPLABMANUL

Page

93

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)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 94: DSPLABMANUL

Page

94

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 13

Title: Binary Amplitude Shift KeyingEquipment 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

s( t )=¿ {A cos (2 πf c t ) binary 1 ¿¿¿¿(1)

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).

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 95: DSPLABMANUL

Page

95

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 96: DSPLABMANUL

Page

96

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 fileUint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling rateshort 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 -1for(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

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),

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 97: DSPLABMANUL

Page

97

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_6713III. Select the Files Category and type for Obj Directory(-fr) D:\Program

files\My Projects\BASK\DebugIV. Select the Advanced Category and select for Memory Models Far

Figure-3 CCS Build options: compiler.

8. Linker OptionClick on Linker (from CCS Build Options).

I. Select the following for the compiler option with Basic (for Category): a) Select Suppress bannerb) Select Exhaustively Read Library c) For Output Filename (-o) type .\Debug\BASK.outd) For Map Filename (-o) type .\Debug\BASK.mape) For Autoinit Model: Select Run-Time Autoinitialization(-c)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 98: DSPLABMANUL

Page

98

Digital Signal Processing Lab Manual

Figure-4 CCS Build options: linker .

9. Building and Running the ProjectI. 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 CCSSelect View GraphTime/Frequency.

V. BASK Signal plot Time-domain plot

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 address of the output buffer is bask_signal. The other options can be left as

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 99: DSPLABMANUL

Page

99

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 100: DSPLABMANUL

Page

100

Digital Signal Processing Lab Manual

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

11. Monitoring the Watch WindowSelect 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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 101: DSPLABMANUL

Page

101

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)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 102: DSPLABMANUL

Page

102

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 14

Title: Linear ConvolutionEquipment Required:TMS 320C6713 Kit.RS232 Serial CablePower CordAIMTo verify Linear ConvolutionTHEORY

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 theTemporary 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 withthe previous output.Step 5 Store the output in the output buffer.Step 6 Repeat the steps from 2 to 5.

Procedure:

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 103: DSPLABMANUL

Page

103

Digital Signal Processing Lab Manual

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 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 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 rateint x[15],h[15],y[15];main(){int i,j,m,n;

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 104: DSPLABMANUL

Page

104

Digital Signal Processing Lab Manual

printf("\n enter value for m");scanf("%d",&m);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 project7. 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_6713III. Select the Files Category and type for Obj Directory(-fr) D:\Program

files\My Projects\Convolution\DebugIV. Select the Advanced Category and select for Memory Models Far

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 105: DSPLABMANUL

Page

105

Digital Signal Processing Lab Manual

Figure-3 CCS Build options: compiler.

8. Linker OptionClick on Linker (from CCS Build Options).

V. Select the following for the compiler option with Basic (for Category): a) Select Suppress bannerb) Select Exhaustively Read Library c) For Output Filename (-o) type .\Debug\ Convolution.outd) For Map Filename (-o) type .\Debug\ Convolution.mape) For Autoinit Model: Select Run-Time Autoinitialization(-c)

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 106: DSPLABMANUL

Page

106

Digital Signal Processing Lab Manual

Figure-4 CCS Build options: linker .

9. Building and Running the ProjectVI. 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 n4Enter values for i/p1 2 3 4Enter Values for n 1 2 3 4

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 107: DSPLABMANUL

Page

107

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

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 108: DSPLABMANUL

Page

108

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 15

Title: Circular ConvolutionEquipment Required:TMS 320C6713 Kit.RS232 Serial CablePower CordAIMTo 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. The256 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];

void main(){ printf(" enter the length of the first sequence\n"); scanf("%d",&m);

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 109: DSPLABMANUL

Page

109

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++) { y[k]=0; /*circular shift*/ for(j=1;j<n;j++)

x2[j]=a[j-1];

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 110: DSPLABMANUL

Page

110

Digital Signal Processing Lab Manual

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 sequence567 Enter the second sequence7854 OUTPUT ;- the circular convolution is

94 110 122 106

Model Graph:-

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 111: DSPLABMANUL

Page

111

Digital Signal Processing Lab Manual

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 112: DSPLABMANUL

Page

112

Digital Signal Processing Lab Manual

University of Central Punjab Faculty of Engineering

Experiment # 16

Title: CORRELATIONEquipment Required:TMS 320C6713 Kit.RS232 Serial CablePower CordAIM: 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 correlationCross 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;

if(m>n)a=m;

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 113: DSPLABMANUL

Page

113

Digital Signal Processing Lab Manual

elsea=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 sequence5enter the length of the second sequence5enter the first sequence5,5,5,5,5,5enter the secound sequence5,5,5,5,5,5the correlation is125,100,75,50,25

OUTPUT:

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)

Page 114: DSPLABMANUL

Page

114

Digital Signal Processing Lab Manual

Prepared by :- ENGR.ZEESHAN SAEED (Lecturer/Lab Engineer)