DSP Unit 6

114
U U U n n n i i i t t t 6 6 6 Content Matlab tutorials

Transcript of DSP Unit 6

Page 1: DSP Unit 6

UUUnnniiittt 666Content

Matlab tutorials

Page 2: DSP Unit 6
Page 3: DSP Unit 6

Labwork

Contents

LAB 1

Unit 1 : Introduction to Matlab Unit 2 : Matlab Basics Unit 3 : One Dimensional Arrays And Graphics Unit 4 : Matrices And Vectors Unit 5 : Scripting And Programming Unit 6 : Introduction TO DSP With Matlab

1 7 14 24 38 53

LAB 2

LTI Discrete – Time System, Convolution And Difference Equations

1-29

Page 4: DSP Unit 6
Page 5: DSP Unit 6

Lab 1

Page 6: DSP Unit 6
Page 7: DSP Unit 6

Unit 1

INTRODUCTION TO MATLAB

Page 8: DSP Unit 6
Page 9: DSP Unit 6

Digital Signal Processing Laboratory

Unit 1 : Introduction to MatLab

Overview

In this chapter, we will learn about:

! What is MatLab?

! Accessing Matlab

! MatLab Environment

! User interface in MatLab

! Input - Output

! File types

! Useful commands

! Common type of errors

Section 1 : What is MATLAB ?

MatLab stands for MATrix LABoratory. It's a software package developed for numerical

calculations and visualization. MatLab was originally developed as a support tool for teaching

matrix calculation - explanation of the name. MatLab today is a very professional tool with

worldwide spread and use in both education and industry.

MatLab has hundreds of built-in functions for numerical calculations, graphics and animation

and in addition to this it comes with a high level programming language giving you an easy

way to develop your own functions and routines. In addition to this a huge amount of

toolboxes, commercial and freeware, are available on the internet

MatLab is an ideal software for studying digital signal processing (DSP). Its language has many

functions that are commonly needed to create and process signals. The plotting capability of

MATLAB makes it possible to visualise the results of processing and gain understanding into

complicated operations.

The purpose of this lab is to help you begin to use MatLab. It is not intended to substitute for

the User's Guide and Reference Guide for MATLAB. You are encouraged to work at the

computer as you read the lab and freely experiment with examples. You should liberally use the

on-line help facility for more detailed information. When using MATLAB, the command help

function name will give information about a specific function. For example, the command help

eig will give information about the eigenvalue function eig. By itself, the command help will

display a list of topics for which on-line help is available; then help topic will list those specific

functions under this topic for which help is available. The list of functions in the last section of

this Primer also gives most of the information. You can preview some of the features of

MATLAB by first entering the command demo and then selecting from the options offered.

1

Page 10: DSP Unit 6

The structure of MatLab and it's facilities is shown here:

Section 2 : Accessing MatLab?

MATLAB can be used in two ways; interactively and non-interactively. In interactive mode,

commands are typed next to the MATLAB command prompt and MATLAB executes each

command as soon as ENTER is pressed.

The non-interactive mode is used for programming. With a text editor, a MATLAB program

can be written. The file must have a *.m suffix (or format), and the program can be executed

using the interactive MATLAB command prompt.

On most systems, after logging in one can enter MATLAB with the system command

matlab and exit MATLAB with the MATLAB command quit or exit. However, your

local installation may permit MATLAB to be accessed from a menu or by clicking an icon. On

systems permitting multiple processes, such as a Unix system or MS Windows, you will find it

convenient to keep both MATLAB and your local editor active. If you are working on a

platform, which runs processes in multiple windows, you will want to keep MATLAB active in

one window and your local editor active in another.

2

Page 11: DSP Unit 6

When you are not sure about a command, use On-line help in MatLab. On-line help is available

from MatLab prompt (a double arrow), by listing all available commands. It is easy, and it is

highly recommended to use this facility. You will get help for a specific MatLab command or

function by writing help subject

Section 3 : MatLab Environment

There are a few things related to the basic facilities in MatLab that will be useful to know, so

here is a short introduction.

A) User Interface in MatLab

The three most important user interface windows in MatLab are :

! Command window. This is the main window in MatLab. Characteristic for this window is

the MatLab command prompt '>>'. All commands are written in this window at the prompt.

Command prompt

! Graphics - output from all graphics commands you write in the command window will open

a new separate window called a figure window. The user can open as many figure windows

as the computer memory allows.

3

Page 12: DSP Unit 6

! Edit window. This is where you write, edit and save your own programs in files called 'm-

files'. You can use any editor you like but MatLab comes with an integrated editor.

B) Input-Output

! Data types

The basic data type in MatLab is an array. An array comprises different data objects: integer,

real numbers, complex numbers, matrices, character strings, structures and cells. Most of the

time it is not necessary to think much about the type of data structure used, MatLab will take

care. As an example you don't need to define whether a variable is real or complex.

! Dimensioning

This is also automatic taken care of in MatLab, meaning that you don't have to define the size

of e.g. matrices and vectors. You find the dimension of an existing vector or matrix with the

commands size and length.

! Case sensitivity

MatLab is case sensitive. So “a” and “A” is two different variables. Most commands and build-

in functions are called using lower case letters. Case sensitivity can be toggled on and off using

the command casesen.

! Command history

MatLab saves previous written commands in a buffer. These commands can be recalled using

'arrow up'. This makes it easier to change previous commands. Another way of using the buffer

is to type the first character in a command and then 'arrow up'.

C) File types

MatLab has 3 types of files where information is saved:

! M-files M-files is standard ASCII text files, with extension .m to the filename. M-files

comes in two different kinds, that is script files and function files. Script file is a collection

4

Page 13: DSP Unit 6

of MatLab commands in a file, executable all in once by typing the file name at the MatLab

prompt. Function file consists a function that may have a number of in- and output

parameters. More on this later on.

! Mat-filer Mat-filer is binary data files, with extension .mat to the filename. Mat-filer is

created by MatLab when using the save command for saving data. This is a file format that

only MatLab can read. Data is loaded into MatLab again using the command load.

! MEX-filer MEX-files is FORTRAN or C programs executable from MatLab, they have

extension .mex. The use of MEX-files takes some routine in using MatLab and we wont

get further in to that subject in this course.

D) Useful Commands

Online help: help shows a list of help topics helpwin opens the interactive help window helpdesk opens web-based help

help subject help on subject

lookfor string makes a list of subjects including string

demo runs the MatLab demo program

Workspace information: (workspace is the memory area where all variables is saved) who shows a list of variables currently in workspace whos shows a list of variables currently in workspace and their dimension what shows list of m-, mat- and mex-files on disk clear erase workspace - all variables are deleted! clear x y z erase only variable x, y and z from workspace clear all erase workspace for both variables and functions

mlock fun lock the function fun so that clear can not erase it from workspace

munlock fun unlock the function fun so that clear can erase it from workspace

clc erase command window, the buffer with the command history is also erased home same as clc clf erase figure window

Directory information's: pwd shows actual work directory cd change aktual work directory dir shows a list of files in the work directory ls same as dir path get or set MatLab search path editpath change MatLab search path copyfile copy file mkdir make new directory

General information's: computer show your type of computer clock return time and date as a date return date as a string ver shows information regarding the installed version of MatLab,

including installed toolboxes

5

Page 14: DSP Unit 6

6

E) Common type of errors

There are a number of errors that new users of MatLab often make and they can cause a lot of

frustration.

! You are not in the correct work directory

! Your are writing and saving m-files, but it seems like MatLab can't find them. If your

files aren't saved in the current work directory MatLab can't find them. Find out which

directory you are working in using pwd. Use dir to check that your files are saved in

this directory. If not change the current work directory, use cd or path; cd is the simpler

one of the two but is only valid until you close down MatLab. Using path you can save

a path to your directory and make MatLab find it every time you start the program.

! You are not saving your files in the correct directory

! When you edit a file in the built-in editor and save it, MatLab doesn't have automatic

access to the directory where you saved your file, go to the first point and correct the

error.

! You are not overwriting your file when you save

! You are running your program by executing an m-file, but something is not working

right so you edit the file and runs again but with the same result. The problem can be

caused by one of the following:

! first possibility is that you forget to save your file after making your corrections in

the file, remember that MatLab gets the file from disk not from memory

! next possible error is that you have more than one m-file having the same name, but

placed in different directories. You are now correcting a file in one directory and

running a file with the same name from another directory

! finally, sometimes the problem may come from lack of memory, this often happens

when working with graphics. A simple way to get around this problem is to erase

workspace using the command clear all

Page 15: DSP Unit 6

Unit 2

MATLAB BASICS

Page 16: DSP Unit 6
Page 17: DSP Unit 6

Digital Signal Processing Laboratory

Unit 2 : MatLab Basics

Overview

The objective of this chapter is, that you learn to start MatLab, make some simple calculations

and finally closing MatLab again

In this chapter, we will learn about:

! How to use on-line help and record a session.

! How to assign a value to a variable and saving these values.

! How to perform simple arithmetic functions such as:

+ addition

- subtraction

* multiplication

/ division and

^ power

! How to suppress printing of the results to the screen.

! How to control the format of calculated values.

! How to close MatLab.

Starting MatLab

Start MatLab by double-clicking it's icon on the desktop. You can also use the Start menu and

find MatLab in the group Programs. When you see the MatLab command window on the

screen, you are ready to go to work.

Underneath is some commands and their output. Start trying the commands in your own

MatLab and see if you can reproduce the results, remember text in italic is what you type in

MatLab and text in bold is the output you should get.

1) On-line help

Use when unsure about a command. Types help and hit 'Return'.

>> help

HELP topics: matlab\general - General purpose commands. matlab\ops - Operators and special characters. matlab\lang - Programming language constructs. matlab\elmat - Elementary matrices and matrix manipulation. matlab\elfun - Elementary math functions. matlab\specfun - Specialized math functions.

...........

For more help on directory/topic, type "help topic".

7

Page 18: DSP Unit 6

You could use on-line help for a specific command

>> help cos

COS Cosine. COS(X) is the cosine of the elements of X.

2) Recording your session

Sessions are recorded using the diary command, in this case a file named “session” that will be

stored in :\Matlab\work\session

>> diary session

3) Variables:

MATLAB has built-in variables like pi, eps, and ans. You can learn their values from the

MATLAB interpreter. In MATLAB all numerical computing occurs with limited precision,

with all decimal expansions being truncated at the sixteenth place [roughly speaking].

The machine's round-off, the smallest distinguishable difference between two numbers as

represented in MATLAB, is denoted "eps". Notice that the result is saved in a variable called

ans. The variable ans will keep track of the last output which was not assigned to another

variable.

>> eps

ans =

2.2204e-016

>> pi

ans =

3.1416

>> help pi

PI 3.1415926535897.... PI = 4*atan(1) = imag(log(-1)) = 3.1415926535897....

You can also assign the value of an expression to a variable. The equality sign is used.

>> x = 6

x = 6

Note :- Variables in MatLab are case sensitive. Therefore variables “x” are distinct from “X”.

8

Page 19: DSP Unit 6

Active variables: At any time if you wanted to know the active variables, we use who:

>> who

Your variables are: ans x y z

Removing a variables by clear :

>> clear x

You could save the value of the variable “x” to a plain text file named “x-value” by

>> save x.value x –ascii

To save all variables in a file named mysession.mat, in a reloadable format, you could use

>> save mysession

4) Variable arithmetics:

MATLAB uses some fairly standard notation. Also you can include comments in your code by

using the "%" sign.

>> 2+3 % this is addition

ans = 5

Powers are performed before division and multiplication, which are done before subtraction and

addition.

>> 2+3*4^2 % power are performed first !

ans = 50

Note:

2+3*4^2 ==> 2 + 3*4^2 <== exponent has the highest precedence

==> 2 + 3*16 <== then multiplication operator

==> 2 + 48 <== then addition operator

==> 50

A semicolon in the end of a line will suppress output to the screen.

>> y = 2^3 + log(pi)*cos(x);

But MatLab still makes the calculation and save the value of y, so you can see the value just by

typing y and hit 'Return'.

>> y

y = 9.0991

9

Page 20: DSP Unit 6

Built-in Mathematical functions

MATLAB has a platter of built-in functions for mathematical and scientific computations. Here

is a summary of relevant functions, followed by some examples:

functions Inverse functions

MatLab name Meaning MatLab Name Meaning Solution in the interval

sin(x) sine to x acos(x) arccosine to x 0 to "

cos(x) cosine to x asin(x) arcsine to x - " /2 to " /2

tan(x) tangent to x atan(x) arctangent to x - " /2 to " /2

atan2(y,x) four-quadrant

arctangent to y/x - " to "

exp exponential

log Natural log

log10 Log base 10

From the equation calculating y it seems that MatLab has the trigonometric functions built-in.

Here we have arcsin taken in –1:

>> theta = asin(-1)

theta = -1.5708

The format for the results printed on screen can be controlled with the command format. Here

you see three examples:

>> format short e >> theta theta = -1.5708e+000 >> format long >> theta theta = -1.57079632679490

>> format compact >> theta theta = -1.57079632679490

Note: The "format compact" command elimiates spaces between the lines of output.

Standard print format is restored by using the command format without a parameter.

>> format >> theta theta = -1.5708

10

Page 21: DSP Unit 6

5) Command-Line Editing

The arrow keys allow "command-line editing," which cuts down on the amount of typing

required, and allows easy error correction.

Parentheses may be used to group terms, or to make them more readable. For example:

>> (2+3*4^2)/2

ans = 25

Almost there with the first lesson, all you need to do now is to shut down MatLab. You can do

this by finding Exit in the menu Files, or by typing quit at the prompt.

>> quit

If you would like to know more about the basic in MatLab, try help in the MatLab program.

Click “?” and the help window will open. In the chapter Learning MatLab you will find

Getting Started, the first two paragraphs Introduction and Development Environment gives a

quick overview, if you are ready to go more in depth then chose the chapter Using MatLab

instead, here you will find a thorough description in the paragraph Development Environment.

Exercise 2.1 : Arithmetic operations

Calculate the following expressions in MatLab:

a) 18

76

6

#

b) 4)15(

15)3(

3#

$

#

Hint :- square root x can be calculated by using the function sqrt(x) or as x^0.5

c) Volume = where r =

Note : " is equal to pi in MatLab

3

.r" 12

. #"

Exercise 2.2 : Functions - Exponential and logarithmic

Exponential and log functions ex, ln x and log x could be calculated in MatLab by using

functions exp(x), log(x) or log10(x). Calculate the following expressions:

a) e3, ln(e

3), log10(e

3) and log10(10

5)

b) 66"e

11

Page 22: DSP Unit 6

c) Solve the equation 3x = 19 and control the result.

The solution is x = ln(19)/ln(3). You can control the result by substituting i the left side of the

equation.

Exercise 2.3 : Functions - Trigonometry

Calculate:

a) sin "/6, cos ", tan "/2

b) sin2 "/6 + cos

2 "/6

c) y = cosh2 x – sinh

2 x, let x = 32"

Exercise 2.4: Complex numbers

In MatLab the letters i and j is used to represent the imaginary operator in complex numbers. A

complex number 2 + 5i can be types in different ways, e.g. 2+5i and 2+5*i. The first example

will always be interpreted as a complex number, the second will only work if i hasn't been

assigned a value and therefore has become a variable. Same rule apply to j.

Calculate:

a) i

i

41

41

#

$

Control the result by calculating by hand.

b) )4

.exp("

i

Control the Euler formula eix

= cos x + i sin x, by calculating the expression using the right

side of the formula.

c) Carry out these to calculations: exp(pi/2*i) and exp(pi/2i). Can you explain the difference

between the results?

12

Page 23: DSP Unit 6

13

Suggested Solution to Exercises in Chapter 2

Commands

Exercise 2.1

a. 7^6/(8^7-1)

b. 3*(sqrt(5)-1)/(sqrt(5)+1)^3-4

c. volume = pi*(pi^(2)-1)^3

Exercise 2.2

a. exp(3)

b. exp(pi*sqrt(66))

c.

a. sin(pi/6)

b. (sin(pi/6))^2+(cos(pi/6))^2

c.

a. (1+4i)/(1-4i)

b. exp(i*pi/4)

c. exp(pi/2*i)

log(exp(3))

log10(exp(3))

log10(10^5)

x = log(19)/log(3)

3^x

Exercise 2.3

cos(pi)

tan(pi/2)

x=32*pi; y=(cosh(x))^2-(sinh(x))^2

Exercise 2.4

cos(pi/4) + i*sin(pi/4)

exp(pi/2i)

Explanation:

exp("/2*i) = e(" /2)·i

= cos("/2) + i sin("/2)

exp("/2i) = e"/(2·i)

= e-(" /2)·i

= cos("/2) - i sin("/2)

Results

Exercise 2.1

a. 0.0561

b. -3.8906

c. 2.1921e+003

Exercise 2.2

a. 20.0855

3

1.3029

5

b. 1.2141e+011

c. x = 2.6801

19.0000

Exercise 2.3

a. 0.5000

-1

1.6332e+016

b. 1

c. y =0

Exercise 2.4

a. -0.8824 + 0.4706i

b. . 0.7071 + 0.7071i

0.7071 + 0.7071i

c. 0.0000 + 1.0000i

0.0000 - 1.0000i

Page 24: DSP Unit 6
Page 25: DSP Unit 6

Unit 3

ONE DIMENSIONAL ARRAYS

AND GRAPHICS

Page 26: DSP Unit 6
Page 27: DSP Unit 6

Digital Signal Processing Laboratory

Unit 3: One-dimensional arrays and graphics

Overview

The objective of this chapter is to learn how to enter one-dimensional arrays and vectors, how

to do arithmetic and trigonometric operations on them, and finally that you learn how to make a

simple 2-D plot

In this chapter, we will learn about:

! How to enter arrays and vectors

! How to enter a vector with n even distributed numbers between a and b

! How simple arithmetic vector functions are done

! How array operations are done. The arithmetic array operators are:

.* Element-by-element multiplication

./ Element-by-element division and

.^ Element-by-element power

! How to use trigonometric functions with arrays as argument

! How do calculate the inner product (dot product) of vectors

! How to plot a signal with grid and labels on the axis

A) Starting MatLab

Start MatLab by double-clicking it's icon on the desktop. You can also use the Start menu and

find MatLab in the group Programs. When you see the MatLab command window on the

screen, you are ready to go to work. Remember text in italic is what you type in MatLab and

text in bold is the output you should get. Assume “format compact” is used in this lab

B) Entering an array

A series of orderly numbers x1, x2, x3... xn, can be created in MatLab using an array. For

example let us define an array that contain the first 6 prime numbers:

>> format compact

>> prime_numbers=[2 3 5 7 11 13] % define using spaces after each number entered

prime_numbers = 2 3 5 7 11 13

You can also use a comma for creating this array by:

>> prime_numbers=[2, 3, 5, 7, 11 13] % define by using comma after each number

prime_numbers = 2 3 5 7 11 13

The elements in an array is identified by their index, for example:

>> prime_numbers(2)

ans = 3

>> prime_numbers(6)

ans = 13

14

Page 28: DSP Unit 6

An array always starts with index = 1. The number of elements in an array is determined using

the function length:

>> length(prime_numbers)

ans = 6

It is also possible to enter the elements in an array one-by-one by: (first we clear the array)

>> clear prime_numbers % to delete or clear the array before we re-enter the value one by one >> prime_numbers(1)=2

prime_numbers = 2 >> prime_numbers(2)=3

prime_numbers = 2 3 >> prime_numbers(3)=5

prime_numbers = 2 3 5 >> prime_numbers(4)=7

prime_numbers = 2 3 5 7 >> prime_numbers(5)=11

prime_numbers = 2 3 5 7 11

>> prime_numbers(6)=13

prime_numbers = 2 3 5 7 11 13

As you can see MatLab keeps track of the size of the array and it is increased by 1 every time

we enter a new element. This operation takes relatively long time to perform and should be

avoided, especially if you work with very large arrays. In most cases it will be an advantage to

reserve memory by creating an array with the appropriate size and fill it with zeroes to start

with.

C) Adding and subtracting an array

Addition and subtraction of arrays is per definition done element-by-element. Lets make a new

array with 6 elements to add to and subtract from the array of prime numbers:

>> normal=[1 2 3 4 5 6]

normal = 1 2 3 4 5 6

>> prime_numbers + normal

ans = 3 5 8 11 16 19

>> prime_numbers – normal

ans = 1 1 2 3 6 7

D) Array with even distribution with colon operator

The colon operator ( : ) is useful for creating index arrays, creating vectors of evenly spaced

values, and accessing submatrices. Use help colon for details.

The colon notation can be generated by giving a start, an increment and end: i = start:increment:end

15

Page 29: DSP Unit 6

An array with n even distributed numbers between a and b can be entered by giving the first

element a, after this the increment and finally the last element b. For example, an array with the

8 even numbers:

>> even= 4: 2: 18 even = 4 6 8 10 12 14 16 18

And an array with the 8 odd numbers

>> odd= 3: 2: 17 odd = 3 5 7 9 11 13 15 17

Negative numbers and decimal numbers can also be used as the increment. If the increment is 1

you can omit it.

>> normal = 1:1:8 normal = 1 2 3 4 5 6 7 8 >> normal = 1:8 % same as above by omitting the 1 normal = 1 2 3 4 5 6 7 8 >> normal = 1:-1:-10 % negative number decrement or increment ! normal = 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10

E) Multiplication and division

If you wish for multiplication or division operations to be done element-by-element you will

need the special array operators '.*' and './'. If we multiply respectively divide the even numbers

with the odd numbers, we get:

>> even.*odd ans = 12 30 56 90 132 182 240 306 >> even./odd ans = Columns 1 through 7 1.3333 1.2000 1.1429 1.1111 1.0909 1.0769 1.0667 Column 8 1.0588

The same rule applies to calculating powers. If we would like to determine the 2nd power of

every element in the array containing the even numbers, we type:

>> even.^2

ans = 16 36 64 100 144 196 256 324

16

Page 30: DSP Unit 6

F) Assigning array to MatLab built-in functions

Built-in functions take an array as argument. The result will be a new array with the value of

the function calculated for each element in the original array. For example:

>> angle=0:20:180

angle = 0 20 40 60 80 100 120 140 160 180

>> angle=pi*angle/180 % to convert from degrees to radian

angle = Columns 1 through 7 0 0.3491 0.6981 1.0472 1.3963 1.7453 2.0944 Columns 8 through 10 2.4435 2.7925 3.1416

>> cos(angle)

ans = Columns 1 through 7 1.0000 0.9397 0.7660 0.5000 0.1736 -0.1736 -0.5000 Columns 8 through 10 -0.7660 -0.9397 -1.0000

>> sin(angle)

ans = Columns 1 through 7 0 0.3420 0.6428 0.8660 0.9848 0.9848 0.8660 Columns 8 through 10 0.6428 0.3420 0.0000

G) Turning array into vector

In MatLab we work with two types of vectors, that is row-vectors (those we used so far), and

column-vectors. A column-vector is defined almost the same way as a row-vector, we just use a

semicolon as element divider in stead of the comma. We can define the six first prime numbers

again, this time in a column-vector:

>> prime_numbers_column=[2; 3; 5; 7; 11; 13]

prime_numbers_column = 2 3 5 7 11 13

En row-vector can be converted to a column-vector and visa versa by transposing. This

operation is done in MatLab using apostrophe: >> A = [1 3 5 7 9 11 13] % First we make us a row-vector called A A = 1 3 5 7 9 11 13 >> At = A' % Here A is transposed to become a column-vector At = 1 3 5 7 9 11 13

17

Page 31: DSP Unit 6

Now we can calculate the inner product of the two vectors. This is done in MatLab using the

ordinary '*' between a row-vector and a column-vector with the same number of elements.

Calculating the inner product of A and the transpose of A can be done in two ways: >> A*At ans = 455 >> A*A' ans = 455

H) Plots and graphics

MATLAB is capable of producing two or three-dimensional plots, it can also display images,

create and play movies. We will mostly need plot and stem functions, which will take two

vectors, one for the x-axis the other for the y-axis.

GRAPHICS FUNCTIONS

Function Description

plot(x,y) 2-D plots y vs. x

stem(x,y) produces a "lollipop" plot of y vs. x – 2-D discrete

subplot(3,2,tile_number) produces a 3x2 tiling of the figure window with the next

plot directed to a tile_number specified

plot(x,y1,x,y2,x,y3) plots y1, y2 and y3 vs x on the same graph

plot3(x,y,z), mesh(x,y,z), surf(x) 3-D plot

xlabel('x axis label') labels x axis

ylabel('y axis label') labels y axis

title ('title of plot') puts a title on the plot

gtext('text')

activates the use of the mouse to position a crosshair on the

graph, at which point the 'text' will be placed when any key

is pressed.

print filename.ps saves the plot as a black and white postscript file

print -dpsc name-of-figure.ps save the plot in a color postscript file

print -dgif8 name-of-figure.gif saves the plot in a "gif" file which can be viewed using "xv"

in Unix.

NOTES:

! MATLAB writes the graphics to figure windows, you can have multiple figure windows

open but only one active. Any plot command executed in the command window will

direct its graphical output to the active window. The command figure(n) will pop up a

new figure window that can be referred to by the number n, or make it active if it

already exists. Control over many of the window attributes (size, location, color, etc.) is

also possible with the figure command.

! When in the graphics screen, pressing any key will return you to the command screen

while the command (show graph):

>> shg

will return you to the current graphics screen

18

Page 32: DSP Unit 6

Next we will see how a simple 2-D plot is created. This is done using the function plot, which

in its simplest form generates a graph with the values in one array as a function of the values in

a second array, assuming that the to arrays has the same numbers of element. Lets generate a

plot of a sine between 0° and 360°: >> x=0: pi/90: 2*pi; >> y=sin(x); >> plot(x,y)

These commands should create a figure showing the one period of a sine wave. Now hit

'Return' and write:

>> grid

Hit 'Return' and write:

>> xlabel('x, radian')

Hit 'Return' again and write:

>> ylabel('sin(x)')

Now you should have a plot looking like this:

To generate an impulse plot, we use:

>> nn =[-10:25] nn = Columns 1 through 12 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 Columns 13 through 24 2 3 4 5 6 7 8 9 10 11 12 13 Columns 25 through 36 14 15 16 17 18 19 20 21 22 23 24 25 >> impulse =(nn==0) impulse = Columns 1 through 12 0 0 0 0 0 0 0 0 0 0 1 0 Columns 13 through 24 0 0 0 0 0 0 0 0 0 0 0 0 Columns 25 through 36 0 0 0 0 0 0 0 0 0 0 0 0 >> stem(nn, impulse)

19

Page 33: DSP Unit 6

Now you should have an impulse function looking like this:

To generate a 3-D plot, we use:

>> t = linspace(0,10*pi); >> plot3(sin(t),cos(t),t) >> xlabel('sin(t)'), ylabel('cos(t)'), zlabel('t') >> text(0,0,0,'Origin') >> grid on >> title('A Helix! ')

Now you should have an impulse function looking like this:

In the MatLab help you will find more information's on making plots in MatLab. Under

Learning MatLab/Getting Started you will find a paragraph named Graphics who will give you

a quick overview, if you want to go more in depth chose the chapter Using MatLab in stead,

here you will find a thorough description in the corresponding paragraph Graphics.

20

Page 34: DSP Unit 6

Exercise 3.1 : Straight line equation The straight-line equation is given by y = mx+c, where m an c are both constants.

a) Calculate y-coordinates for a line with the slope m = 0.8 and intercept c = -5 for the

following x coordinates: x = 0, 1, 2.5, 3, 4, 6, 11 and 12

Notice: your commands should not include the special array operators since we are only talking

about multiplying a vector with a scalar and adding a constant.

b) Make a plot of y-coordinates as a function of the x-coordinates. Using the command

plot(x,y,'*',x,y) you can make a plot showing both the calculated points and the

straight line going through the points. Put labels on both axis, and give the plot a title using the

function title. Read more about using the command plot in the online help function (help

plot)

Exercise 3.2 : Multiplication, division and power a) Create a row-vector t having 12 elements, that is the numbers from 1 - 12. Now calculate:

b) x = 3t cos(t)

c) 5

2

"

"#

t

ty

d) 4

4sin

t

tz #

e) Make a plot of x, y and z as a function of t. Put the three curves on the same plot, make x

red, y green and z blue. Put axis, grid and title on your figure.

Exercise 3.3: Plot an ellipse

All points having the coordinates x = A cos(t) and y = B sin(t), where A and B are constants

and where t is in the interval from 0 to 2$, are placed on an ellipse.

a) Plot an ellipse, e.g. using A = 2, B = 1 and try to interpret the meaning of A and B. You can

try to make more than one ellipse by changing the values of A and B.

Exercise 3.4 : Approximation of a triangle curve A triangle curve being symmetric around t = 0 can be approximated using the Fourier series:

%&

'()

*""""# )9sin(

9

1)7sin(

7

1)5sin(

5

1)3sin(

3

1)sin(

2)(

2ttttt

Atx m +++++

$

where Am is the amplitude for the wave and + is its frequency.

a) Make a plot of the approximate triangle curve using Am = 1 and + = 2$. Put grid, axis and

title on your figure.

21

Page 35: DSP Unit 6

Suggested Solution to Exercises in Chapter 3

Commands

Exercise 3.1

a. x = [0 1 2.5 3 4 6 11 12];

y = 0.8*x-5

b. plot(x,y,'*',x,y)

xlabel('x-axis')

ylabel('y-axis')

title('Linear line y=0.8x-5')

Exercise 3.2

a. t=1:12

b. x=(3*t).*cos(t)

c. y = (t+2)./(t+5)

d. z = sin(t.^4)./t.^4

e. plot(t,x,'r',t,y,'g',t,z,'b')

grid

xlabel('t')

ylabel('x = red, y = green, z = blue')

title('Three functions of t')

Results

Exercise 3.1

a. y = [ -5 -4.2 -3 -2.6 -1.8 -0.2 3.8 4.6]

b.

a. t = [1 2 3 4 5 6 7 8 9 10 11 12]

b. x=[1.6209 -2.4969 -8.9099 -7.8437

4.2549 17.2831 15.8319 -3.4920 -

24.6005 -25.1721 0.1460 30.3787 ]

c. y =[0.5000 0.5714 0.6250 0.6667

0.7000 0.7273 0.7500 0.7692 0.7857

0.8000 0.8125 0.8235]

d. z =[0.8415 -0.0180 -0.0078 -0.0039

0.0003 0.0008 0.0003 -0.0001 0.0001

-0.0000 0.0001 0.0000]

e.

22

Page 36: DSP Unit 6

Exercise 3.2

a. t = 0: 2*pi/100: 2*pi;

x = 2*cos(t);

y = 1*sin(t);

plot(x,y)

grid

title('Ellipse having A=2 og B=1')

Major axis is 2A and minor axis is 2B

Exercise 3.3

a) w = 2*pi;

Am = 1;

t = -1: 0.1: 1;

x = (2*Am)*(sin(w*t)+sin(3*w*t)/3+

sin(5*w*t)/5+ sin(7*w*t)/7+

sin(9*w*t)/9)/pi^2;

plot(t,x)

grid

xlabel('time t')

ylabel('x(t)')

title('Approximated triangular curve')

23

Page 37: DSP Unit 6

Unit 4

MATRICES AND VECTORS

Page 38: DSP Unit 6
Page 39: DSP Unit 6

Digital Signal Processing Laboratory

Unit 4: Matrices and vectors

Overview

The objective of this chapter is to learn how to work with matrices and vectors in MatLab

In this chapter, we will learn about:

! How you create matrices and vectors

! How you index matrices

! How you work with a part of a matrix

! How to use special matrix functions

We are now in essential part of MatLab and it's organization of data. MatLab was originally

developed for teaching matrix algebra, this means that the structure of the program is build for

work with data organized in matrices.

A) Defining Matrices

Matlab is designed to make matrix manipulation as simple as possible. Every Matlab variable

refers to a matrix [a number is a 1 by 1 matrix], for example either of the following statements

will produce the 3x3 matrix A:

>> format compact

>> A = [1,2,3; 4 5 6; 7 8 9] % first method to define a 3x3 matrix A = 1 2 3 4 5 6 7 8 9

>> A = [1 2 3 % second method of defining matrix, hit return key !

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

NOTE:

! The elements of a matrix being entered are enclosed by brackets;

! A matrix is entered in "row-major order" [all of the first row, then all of the second row]

! Rows are seperated by a semicolon [or a newline], and the elements of the row may be

seperated by either a comma or a space.

B) Reading and modifying matrices

The element in the i'th row and j'th column of a is referred or read to in the usual way:

>> A(2,3) % i = row, j = column, in A(i,j) format ans = 6

24

Page 40: DSP Unit 6

It's very easy to modify matrices:

>> A(3,3)=0

A = 1 2 3 4 5 6 7 8 0

>> A(3,3) = 9; % We put the correct value back again.

We could extract or change parts of a matrix. Lets create a C matrix equal to the two bottom

rows in the A matrix:

>> C = A(2:3,1:3)

C = 4 5 6 7 8 9

2:3 indicate elements from row 2 to 3 and 1:3 indicates elements in column 1 to 3, all elements

complying with both conditions will be included. If we need all rows or columns in a matrix,

we can just write a colon since it by itself indicates all elements in the row or column:

>> C = A(2:3,:) C = 4 5 6 7 8 9

One row or column in a matrix can be erased by setting it equal to a null vector []. This is how

column 2 of the C matrix is deleted:

>> C(:,2) = [ ]

C = 4 6 7 0

C) Building matrices from block:

Large matrices can be assembled from smaller matrix blocks. For example, with matrix A in

hand, we can enter the following commands;

>> D = [A; 10 11 12] % generates a (4x3) matrix D = 1 2 3 4 5 6 7 8 9 10 11 12

>> [A; A] % generates a (6x3) matrix

ans = 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9

>> [A, A] % generates a (3x6) matrix

ans = 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9

25

Page 41: DSP Unit 6

There are many built-in matrix constructions. Here are a few:

>> rand(1,3) % generates random (1x3) matrix

ans = 0.9501 0.2311 0.6068

>> rand(2) % generates random (2x2) matrix

ans = 0.4860 0.7621

0.8913 0.4565

>> zeros(3,2) % generates (3x2) matrix of zeros

ans = 0 0 0 0

0 0

>> ones(3,2) % generates (3x2) matrix of ones

ans = 1 1 1 1

1 1

>> eye(3) % generates (3x3)identity matrix

ans = 1 0 0 0 1 0 0 0 1

>> eye(2,3) % generates (2x3)identity matrix

ans = 1 0 0 0 1 0

>> B = [ A, zeros(3,2); zeros(2,3), eye(2) ] % building (5x5) matrix with built-in matrix !

B = 1 2 3 0 0 4 5 6 0 0 7 8 9 0 0 0 0 0 1 0 0 0 0 0 1

D) MATRIX OPERATIONS:

Matrix Operations in MATLAB

Operator Description

+ addition

- subtraction

* multiplication

^ power

' transpose

\ left division

/ right division

These matrix operations apply, of course, to scalars (1-by-1 matrices) as well. If the sizes of the

matrices are incompatible for the matrix operation, an error message will result, except in the

case of scalar-matrix operations (for addition, subtraction, and division as well as for

multiplication) in which case each entry of the matrix is operated on by the scalar

26

Page 42: DSP Unit 6

Matrix Transpose: The transpose of a matrix is the result of interchanging rows and columns.

MATLAB denotes the [conjugate] transpose by following the matrix with the single-quote

[apostrophe].

>> A' ans = 1 4 7 2 5 8 3 6 9

Matrix Addition/Subtraction: Let matrix "A" have m rows and n columns, and matrix "B"

have p rows and q columns. The matrix sum "A + B" is defined only when m equals p and n =

q, The result is a n by m matrix having the element-by-element sum of components in A and B.

>> E = [ 2 3; 4 5.0; 6 7]; >> F = [ 1 -2; 3 6.5; 10 -45]; >> E+F ans = 3.0000 1.0000 7.0000 11.5000 16.0000 -38.0000

Matrix Multiplication: Matrix multiplication requires that the sizes match. If they don't, an

error message is generated

>> E = [ 2 3; 4 5.0; 6 7]; >> G = [ 1 2; 3 4]; >> E*G ans = 11 16 19 28 27 40

Scalars multiply matrices as expected, and matrices may be added in the usual way (both are

done "element by element"):

>> A A = 1 2 3 4 5 6 7 8 9 >> y= 2*A, x=A/4; y = 2 4 6 8 10 12 14 16 18 >> x x = 0.2500 0.5000 0.7500 1.0000 1.2500 1.5000 1.7500 2.0000 2.2500

27

Page 43: DSP Unit 6

Matrix Functions "any" and "all" : There is a function to determine if a matrix has at least

one nonzero entry, any, as well as a function to determine if all the entries are nonzero, all. The

output of these functions are boolean i.e. 1 for True, 0 for False.

ANY :- True if any element of a vector is nonzero.

ALL :- True if all elements of a vector are nonzero.

>> x=zeros(1,6) x = 0 0 0 0 0 0 >> any(x) ans = 0 >> y=ones(1,6) y = 1 1 1 1 1 1 >> any(y) ans = 1 >> all(y) ans = 1

Returning more than One Value : Some MATLAB functions can return more than one value.

For example the max or min functions can return the maximum value in an array as well as its

index:

>> [m, i] = max(A) % returns both the maximum and index of matrix A

m = 7 8 9 i = 3 3 3

>> min(A) ) % returns both the minimum of matrix A

ans = 1 2 3

E) POINTWISE MATRIX OPERATIONS:

The matrix operations of addition and subtraction already operate on an element-by-element

basis, but the other matrix operations given above do not -- they are

matrix operations. MATLAB has a convention in which a dot in front of the operations, * , ^ , \

, and /, will force them to perform entry-by-entry multiplication instead of the usual matrix

operation.

>> [1,2,3,4].*[1,2,3,4] % per entry multiplications

ans = 1 4 9 16

>>[1,2,3,4].^2 % per entry square

ans = 1 4 9 16

28

Page 44: DSP Unit 6

F) EXTRACTING SUBMATRICES:

Suppose we have 9x8 matrix A and we want to extract a 4x3 submatrix, this can easily be done

using the colon operator with A(2:5,1:3). Another example

>> s = rand(20,5); s(6:7, 2:4) ans = 0.4451 0.3028 0.8385 0.9318 0.5417 0.5681

You may wish use this construction to extract "subvectors," as follows

>> B = [1 2 3 0 0

5 6 7 0 0 9 10 11 0 0 0 0 0 1 0 0 0 0 0 1];

>> B(1:12)

ans = 1 5 9 0 0 2 6 10 0 0 3 7

>> B(12:-2:1)

ans = 7 0 10 2 0 5

>> x=10:100;

>> x(40:5:60)

ans = 49 54 59 64 69

A very common use of the colon notation is to extract rows, or columns, as a sort of "wild-card"

operator, which produces a default list. The following command

produces the matrix B, followed by its first row [with all of its columns], and then its second

column [with all of its rows].

>> B(1,:)

ans = 1 2 3 0 0

>> B(:,2)

ans = 2 6 10 0 0

Example

Next we start with a systems of equations:

1x1 + 2x2 + 3x3 = 4

5x1 + 6x2 + 7x3 = 8

9x1 + 10x2 + 10x3 = 12

Here we can define a coefficient matrix A:,

"""""

#

$

%%%%%

&

'

(

10109

765

321

A

29

Page 45: DSP Unit 6

and a result vector B:, """

#

$

%%%

&

'

(

12

8

4

B

Now we could describe the system on the matrix form, AX = B.

Lets enter A and B into MatLab. Matrice is entered row by row. Rows are separated by

semicolon and columns are divided by space or comma.

>> A=[1 2 3; 5 6 7; 9 10 10]

A = 1 2 3 5 6 7 9 10 10 >> B = [4; 8; 12] % B is supposed to be a column-vector so we use ; as the separator B = 4 8 12

One method for solving it is the Cramer rule, which yields the solution using determinants such

as :

Let D1 be the matrix in the numerator. In MatLab we can quickly create the matrix D1 from the

A matrix, by setting the first column equal to the B vector:

>> D1 = A; D1(:,1) = B D1 = 4 2 3 8 6 7 12 10 10

In the same way we name the matrices in the solution of x2 and x3 for D2 and D3. D2 and D3 is

created in the same manner as D1:

>> D2 = A; D2(:,2) = B

D2 = 1 4 3 5 8 7 9 12 10

>> D3 = A; D3(:,3) = B

D3 = 1 2 4 5 6 8 9 10 12

30

Page 46: DSP Unit 6

All we need now is to calculate the determinant for all the matrices, which is rather

cumbersome if we have to do it by hand. In MatLab it's simple, we have a function doing the

trick

>> det(A)

ans = 4

The solution to the system of equations is now found using the Cramer rule:

>> X = [ det(D1); det(D2); det(D3)]/det(A) X = -2 3 0

An easy control is to calculate A multiplied X. This is done like this:

>> A*X

ans = 4 8 12

Which exactly is our vector B, so the solution is correct.

This was a rather complicated way to solve the system of equations, at least from a MatLab

point of view. Since the A matrix is a square matrix and it's determinant is not equal to zero an

inverse matrix exists. The inverse of a matrix is very easy to determine in MatLab, there is a

function available:

>> A_inv = inv(A)

A_inv = -2.5000 2.5000 -1.0000 3.2500 -4.2500 2.0000 -1.0000 2.0000 -1.0000

So the solution to our system of equations is found by multiplying A-inv and the B vector:

>> X = A_inv*B

X = -2.0000 3.0000 -0.0000

Still MatLab offers an even simpler method, Gauss elimination. This is a very effective method

for the numerical solution of systems of equations. The Gauss elimination method is called

using the backslash operator '\':

>> X = A\B % this really means B divided by A

X = -2.0000 3.0000 -0.0000

31

Page 47: DSP Unit 6

Matrix dimensions are automatically calculated by MatLab. You get the dimensions of an

existing matrix A using the command size(A) or more specific [r,s] = size(A) which

will return the number of row in the variable r and number of columns in the variable s:

>> C = magic(5) % creating a special 5x5 matrix

C = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9

>> C(:,2) = [] % and erasing column 2

C = 17 1 8 15 23 7 14 16 4 13 20 22 10 19 21 3 11 25 2 9

>> [r,s] = size(C) % finding r and s

r = 5 s = 4

If we “key-in” a single element or a few numbers of elements in a matrix MatLab will

automatically adjust the size to contain the specified elements. Lets assume that the matrices A

and B is non existent:

>> clear all % we start by erasing all, we want to work with new matrices

>> B(2,3) = 5

B = 0 0 0 0 0 5

>> A(3,1:3) = [1 2 3]

A = 0 0 0 0 0 0 1 2 3

Another instance where initializing is a good idea, is if you are working with matrix elements in

a loop (e.g. for or while) and these elements is to be added to the matrix in each loop. En

null matrix is created like this:

>> A = []

A = []

32

Page 48: DSP Unit 6

To add a row or column to a matrix is quite simple, but can of course only be done if the

dimensions of the row or column to be added fits the existing matrix. Lets try to create a matrix,

a row-vector and a column-vector and then make two new matrices by adding the row and the

column to the original matrix:

>> A = eye(3)

A = 1 0 0 0 1 0 0 0 1

>> u = [ 4 5 6 ]

u = 4 5 6

>> v = [ 2 3 4 ]'

v = 2 3 4

>> B = [A; u]

B = 1 0 0 0 1 0 0 0 1 4 5 6

>> C = [A v]

C = 1 0 0 2 0 1 0 3 0 0 1 4

Exercise 4.1 : Type in matrices Type in the following matrices:

a)

b)

c)

33

Page 49: DSP Unit 6

Exercise 4.2: Controlling rules for linear algebra

a) Is matrix addition commutative? Calculate A + B and B + A. Do you get the same results?

b) Is matrix addition associative? Calculate (A + B) + C and A + (B + C) in that order. Do you

get the same results?

c) Is multiplication with a scalar distributive? Calculate (A + B) and A + B using = 5 and

show that the result is the same.

d) Is multiplication with a matrix distributive. Calculate A*(B + C) and compare with A*B +

A*C.

e) Matrices behave different than scalars! For scalars this rule apply, if a·b = a·c then b = c if a

is not equal to zero. Does this rule apply to matrices? Control by calculating A·B and A·C.

Exercise 4.3: Create matrices med zeros, eye and ones

Create the following matrices using the functions zeros, eye and ones. If necessary use

online help for these functions (e.g. help eye):

a)

b)

c)

Exercise 4.4: Create a large matrix using

Create the following matrix G only by the use of matrix functions and the three matrices A, B

and C from problem 1.

34

Page 50: DSP Unit 6

Exercise 4.5: Matrix manipulation

Do the following operations on matrix G created in Problem 4:

a) Erase the last row and the last column in the matrix.

b) Extract a part matrix consisting the first 4x4 matrix in G.

c) Replace G(5,5) with 4.

d) What result will you get if you write G(14) and hit 'Return'? Can you explain how MatLab

get this result?

e) What happens if you write G(12,1) = 1 and hits 'Return'?

Suggested Solution to Exercises in Chapter 4

35

Commands

Exercise 4.1

a) A = [ 2 6; 3 9]

b) B = [ 1 2; 3 4]

c) C = [-5 5; 5 3]

Results

Exercise 4.1

a A =

2 6

3 9

b B =

1 2

3 4

c C =

-5 5

5 3

Exercise 4.2

a) A+B

B+A

b) (A+B)+C

A+(B+C)

c) 5*(A+B)

5*A+5*B

Exercise 4.2

a) ans =

3 8

6 13

ans =

3 8

6 13

b) ans =

-2 13

11 16

ans =

-2 13

11 16

c) ans =

15 40

30 65

ans =

Page 51: DSP Unit 6

d) A*(B+C)

A*B+A*C

e) A*B

A*C

15 40

30 65

d) ans =

40 56

60 84

ans =

40 56

60 84

e) ans =

20 28

30 42

ans =

20 28

30 42

Exercise 4.3

a) D = zeros(2,3)

b) E = 5*eye(3)

c) F = 3*ones(2,2)

Exercise 4.3

a) D =

0 0 0

0 0 0

b) E =

5 0 0

0 5 0

0 0 5

c) F =

3 3

3 3

Exercise 4.4

G = A

G(3:4,3:4) = B

G(5:6,5:6) = C

Exercise 4.4

G =

2 6

3 9

G =

2 6 0 0

3 9 0 0

0 0 1 2

0 0 3 4

G =

2 6 0 0 0 0

3 9 0 0 0 0

0 0 1 2 0 0

0 0 3 4 0 0

0 0 0 0 -5 5

0 0 0 0 5 3

Exercise 4.5

a) G(6,:) = []; G(:,6) = []

Exercise 4.5

a) G =

2 6 0 0 0

3 9 0 0 0

0 0 1 2 0

36

Page 52: DSP Unit 6

37

b) G(1:4,1:4)

c)G(5,5) = 4

d) G(14)

The elements is also indexed in succession column

by column

e) G(12,1) = 1

0 0 3 4 0

0 0 0 0 -5

b) ans =

2 6 0 0

3 9 0 0

0 0 1 2

0 0 3 4

c) G =

2 6 0 0 0

3 9 0 0 0

0 0 1 2 0

0 0 3 4 0

0 0 0 0 4

d) ans =

3

e) G =

2 6 0 0 0

3 9 0 0 0

0 0 1 2 0

0 0 3 4 0

0 0 0 0 4

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

1 0 0 0 0

Page 53: DSP Unit 6

Unit 5

SCRIPTING AND PROGRAMMING

IN MATLAB

Page 54: DSP Unit 6
Page 55: DSP Unit 6

Digital Signal Processing Laboratory

Unit 5: Scripting and programming in MatLab

Overview

The objective of this chapter is to learn how to create and execute script files and functions in

MatLab

A script file is user-defined file consisting a series of MatLab commands. The file must be

saved with the extension '.m', that will make it a m-file. A script file is executed by writing its

name (without the extension '.m') at the MatLab command prompt

A function file is also a m-file, just like a script file, the difference is that a function file has a

function definition in the first line, defining input and output for the function.

In this chapter, we will learn about:

! How to create, write and save a script file

! How to execute a script file in MatLab

! How to distinguish between a script file and a function file

! How to open and edit an existing m-fil

! How to create and execute a function file in MatLab

A) Making a script file

First thing we will do is to make a script file that can draw a sinusoidal waveform. In order to

do this carry out the following:

1. Create a new file, you can do this by selecting the menu File|New|M-file, this will

open the built-in editor in MatLab. You can also use an ordinary text editor like

Notebook.

2. Key in the following commands in the file. Lines starting with the % sign is interpreted

by MatLab as comments and they will be ignored when the files is executed

% x(t) = sin(pi/8)t for 0<=t<=100

% x(t) = 0 for 101<=t<=200

% Written by : Wong Sew Kin

% Last modified : 02/12/02

%--------------------------------------------------------

% The first lines in a file with the %-sign is interpreted as a help text

t = 0:200; % number of points to be plotted, increment by 1

x = sin((pi/8)*t); % calculate x for t=0 to 100

x(101:200)=zeros(1,100) % value for x=0 for t=101 and above

plot(t,x) % plot the 2D graph

grid % put grids in the graph

title('x(t)') % put title

xlabel('Time') % label for x-axis

ylabel('Amplitude') % label for y-axis

3. Save the file with the name sinus.m

4. Go back to the MatLab command window, here you can execute your script file by

writing:

38

Page 56: DSP Unit 6

>> help sinus

A script file drawing a sinusodial waveform x(t) = sin(pi/8)t for 0<=t<=100 x(t) = 0 for 101<=t<=200 Written by : Wong Sew Kin Last modified : 02/12/02 --------------------------------------------------------

Here you can see that the first lines in the file starting with the %-sign is interpreted as help text

and displayed when using the help function. Now execute the file by writing its name in the

command line:

>> sinus

This should produce a figure window with a plot looking like this:

This method works well, it does though have one drawback, the syntax is not controlled while

writing the script file, this is first done when the file is executed in MatLab. If there is any

errors you will have to enter the editor again and correct until all errors is eliminated.

39

Page 57: DSP Unit 6

If you prefer to have the syntax controlled immediately there is a way to create the m-file while

MatLab is active. This is done using the command diary FileName. This command will save all

screen activity, errors and output included in the file FileName until you write diary again.

After this you can open the file in the editor and make the nessecary corrections, making the

file a proper script file.

Let’s try an example, we will create a file sketch.m by using the diary command:

>> diary sketch.m

>> [x y] = meshgrid(-3:.1:3, -3:.1:3);

>> z = x.^2 - y.^2;

>> meshi(x,y,z)

??? Undefined function or variable 'meshi'.

>> mesh(x,y,z)

>> diary

Two things worth noticing about the file created:

! The error message coming because we wrote meshi in stead of mesh will also be in

the file

! The last command diary, is also in the file

All these "errors" must be corrected in the file sketch.m. Open the file and correct the errors,

then save the file again and finally execute it to see that it works:

>> edit sketch.m

>> sketch

B) Programming in MatLab

MATLAB supports functional programming and provides relational and logical constructs as

well as branching and looping constructs:

RELATIONAL & LOGICAL CONSTRUCTS

Operator Description

< less than

> greater than

<= less than or equal

>= greater than or equal

== equal

~= not equal

& and

| or

~ not

NOTE: "=" is used in an assignment statement while "= =" is used in a relation.

40

Page 58: DSP Unit 6

Examples: When applied to scalars, a relation produces 1 for true or 0 for false:

>> 3 < 5

ans = 1

>> a = 3 == 5

a = 0

When logical operands are applied to matrices of the same size, a relation is a matrix of 0's and

1's giving the value of the relation between corresponding entries.

>> A = [ 1 2; 3 4 ]; >> B = [ 0 7; 8 9 ]; >> A == B ans = 0 0 0 0 >> A < B ans = 0 1 1 1

To see how the other logical operators work

>> A = [ 1 0; 0 1]; >> B = [1 1; 0 0]; >> ~A

ans = 0 1 1 0 >> A&B

ans = 1 0 0 0 >> A|B

ans = 1 1 0 1 >> A|~A

ans = 1 1

1 1 >> A&~B ans =

0 0

0 1 >> B|~A ans = 1 1 1 0

41

Page 59: DSP Unit 6

BRANCHING CONSTRUCTS

If-end

if <condition>,

<program>

end

If-else-end

if <condition>,

<program 1>

else

<program 2>

end

If-elseif-end

if <condition 1>,

<program 1>

elseif

<condition 2>,

<program 2>

end

NOTE: The condition is a logical expression that will evaluate to either true or false (i.e., with

values 1 or 0). When the logical expression evaluates to 0, the program control moves on to the

next program construction.

Example:

>> a = 1; >> b = 2; >> if a < b, c = 3; end; >> c c = 3

LOOPING CONSTRUCTS

For Loop

for i = 1:n,

<program>,

end

Program will execute n times with i having values 1 to

n with increments of 1.

For Loop

with

Vector

for i = [2,4,5,6,10],

<program>,

end

Program will execute 5 times with i = 2, 4, 5, 6, 10.

For Loop

with

Matrix

for i = magic(7),

<program>,

end

Program will execute 7 (=number of columns) times,

and the values of i used in program will be

successively the columns of magic(7).

While

Loop

while <condition>,

<program>,

end

Program will execute as long as condition is true.

Example : The basic for loop. The following computes and prints "c = 2*i" for i = 1, 2, ... 5.

42

Page 60: DSP Unit 6

>> for i = 1 : 5, c = 2*i end c = 2 c = 4 c = 6 c = 8 c = 10

You can also nest looping constructs. The following example creates the matrix contents inside

a nested for loop

>> or i=1:10,

for j=1:10, A(i,j) = i/j; end end

>> A

A = Columns 1 through 7 1.0000 0.5000 0.3333 0.2500 0.2000 0.1667 0.1429 2.0000 1.0000 0.6667 0.5000 0.4000 0.3333 0.2857 3.0000 1.5000 1.0000 0.7500 0.6000 0.5000 0.4286 4.0000 2.0000 1.3333 1.0000 0.8000 0.6667 0.5714 5.0000 2.5000 1.6667 1.2500 1.0000 0.8333 0.7143 6.0000 3.0000 2.0000 1.5000 1.2000 1.0000 0.8571 7.0000 3.5000 2.3333 1.7500 1.4000 1.1667 1.0000 8.0000 4.0000 2.6667 2.0000 1.6000 1.3333 1.1429 9.0000 4.5000 3.0000 2.2500 1.8000 1.5000 1.2857 10.0000 5.0000 3.3333 2.5000 2.0000 1.6667 1.4286 Columns 8 through 10 0.1250 0.1111 0.1000 0.2500 0.2222 0.2000 0.3750 0.3333 0.3000 0.5000 0.4444 0.4000 0.6250 0.5556 0.5000 0.7500 0.6667 0.6000 0.8750 0.7778 0.7000 1.0000 0.8889 0.8000 1.1250 1.0000 0.9000 1.2500 1.1111 1.000

There are actually two loops here, with one nested inside the other; they define A(1,1), A(1,2),

A(1,3) ... A(1,10), A(2,1), ... A(10,10) in that order.

43

Page 61: DSP Unit 6

NOTE: A relation between matrices is interpreted to be true if each entry of the relation matrix

is nonzero. Hence, if you wish to execute a statement when matrices A and B are equal you

could type

if A == B

statement

end

but if you wish to execute statement when A and B are not equal, you would type

if any(any(A ~ B))

( statement )

end

or, more simply,

if A == B else

{ statement }

end

C) Functions & Function Files

Function files can be compared to procedures in Pascal or functions in C. When you gain

confidence in using MatLab you will realize that most of you time working with the program

will be spend on writing and improving your own function files.

A function file always starts with a function definition in the first line. The function definition

line informs MATLAB that the M-file contains a function, and specifies the in- and outputs of

the function. Without this line the file become a script file. The syntax for the function

definition is:

function [output variables] = function_name(input variables);

The function_name must be the same as the name of the file (without .m extension) the function

is written in. If we want to write a function named zeropoint then the m-file containing that

function must be named zeropoint.m. The function definition line can have different looks,

dependent on the number of outputs. Here are some examples:

Function definition line Filename Number of input number of output

function [] = sinus(r); sinus.m 1 0

function sinus(r); sinus.m 1 0

function [rho,H,F] = motion(x,y,t); motion.m 3 3

function [theta] = angleTH(x,y); angleTH.m 2 1

function theta = THETA(x,y,z); THETA.m 3 1

44

NOTICE: the first word in the line function must be written with lower case. It's a very

common mistake to write Function.

Page 62: DSP Unit 6

Now we shall try to make a function file that will draw a circle with a specified radius thus

having the radius as an input to the function. You can either write the function file all the way

from scratch, or you can edit the script file from Lesson 4. The last being the easiest, so this is

what we will do.

! Open the file sinus.m, do this by choosing the menu File|Open. Find the correct file

in the dialog box and open the file. This will open the MatLab editor and the

contents of the file sinus.m should be shown in the editor.

! Edit the file sinus.m, making it look like this:

function [x] = sinus1(f);

% A script file drawing a sinusodial waveform

% x(t) = sin(pi/8)t for 0<=t<=100

% x(t) = 0 for 101<=t<=200

% Written by : Wong Sew Kin

% Last modified : 02/12/02

%--------------------------------------------------------

% The first lines in a file with the %-sign is interpreted as a help text

t = 0:200; % number of points to be plotted, increment by 1

x = sin((pi/8)*t*f); % calculate x for t=0 to 100

x(101:200)=zeros(1,100) % value for x=0 for t=101 and above

plot(t,x) % plot the 2D graph

grid % put grids in the graph

title(['x(t)when f is',num2str(f)]) % put title

xlabel('Time') % label for x-axis

ylabel('Amplitude') % label for y-axis

! Save the file with the name sinus1.m, by choosing File|Save As...

! There are different ways to execute the file such as:

>> f = 10; >> [x] = sinus1(f) >> [cx] = sinus1(15) >> sinus1(25) >> sinus1(f^2/(f+5*sin(f)))

Other example : Here we create a file named "sqroot.m" containing the following lines

function sqroot(x)

% SQROOT Compute square root by Newton's method

% Initial guess

xstart = 1;

% Iteration loop to compute square root

for i = 1:100

xnew = ( xstart + x/xstart)/2;

disp(xnew);

if abs(xnew - xstart)/xnew < eps, break, end;

xstart = xnew;

end

45

Page 63: DSP Unit 6

With the function m-file in place, we can give the MATLAB commands

>> format long

>> sqroot(20)

10.50000000000000

6.20238095238095

4.71347454528837

4.47831444547438

4.47214021706570

4.47213595500161

4.47213595499958

4.47213595499958

Now you should be able to tell the major differences between function files and script files,

namely that the function file is having a function definition line as the first line in the file. But

there are other differences between the two type of files.

Variables

There is an important difference between the way variables are treated in function files an in

script files. Variables defined in a function file are local and they are erased from MatLab

Workspace after the execution of the file, whereas variables in a script file are global and

therefore remain in Workspace after the execution of a script file.

Executing a function in another function

In most cases it is no trouble at all. In our circle function above we used several of the built-in

MatLab functions (linspace, sin, cos, plot, axis, title). We used them in exact the same way as if

we had been writing them at the MatLab prompt or in a script file. This applies for all

functions, built-in as well as user defined.

The only case where this doesn't apply is if we need to make a dynamic function call, that is if

we don't want to call the same function each time. If we need to make a dynamic function call,

the function name for the function we want to call must be an input parameter in the form of a

text string. E.g. the built-in function fzero finds a zero point for a function in one variable.

The function call to this function is fzero(f,x), where f is the function name and x is an

initial guess on the solution. Lets say we write a function called f2 (save in the file f2.m) where

f(x) = 2x2-3x+2, the we can call fzero using the parameters fzero('f2',1). Notice the

single quotation marks surrounding f2 (they make the input interpreted as a string).

When we write a function that is supposed to call a dynamic function we use the function feval

to do this. E. g. [y,z] = feval('f',x,t); will evaluate the function f having the input variables x and

t. This command corresponds to writing [y,z] = f(x,t) at the command prompt. Learn more

about feval by writing help feval at the MatLab command prompt.

46

Page 64: DSP Unit 6

Exercise 5.1: Creating Script file Create a script M-file that sets a=2, b=5 and outputs c=a+b. Call this M-file “Add2and5.m”.

Exercise 5.2: Creating function

a) Create a function M-file with x and y as inputs and z = x + y as output. Call this M-file

'Adder.m'. Test your function m-file.

b) Create a function M-file that takes matrices A and B as input arguments and outputs the

matrix C=A*B. Call this M- file “multipier.m”. Try your function on some test cases.

c) Use a function M-file to create a function f(x) = x2 –2 x –2. Test your function to see if it

does what you expect. Plot the function f(x) for x between –2 and 2.

Exercise 5.3: Normal Application of Functions and Scripts

The mechanical work W done in using a force to push a block through a distance D is W = FD.

The following table gives data on the amount of force to push a block through the given

distance over 5 segments of a certain path. The force varies because of the differing friction

properties of the surface.

Path Segment 1 2 3 4 5

Force (N) 400 550 700 500 600

Distance (m) 2 0.5 0.75 1.5 3

Use MATLAB to find

a. the work done over each segment of the path

b. the total work done over the entire path

Create both a script m-file and a function m-file to perform the calculations.

Exercise 5.4: Script file for solving a system of equations Write a script file, solvex.m, that can be used for solving this system of equations:

or A·x = b. As you can see A depends on the parameter r, and the file solvex.m must be capable

of solving the system of equations for different values of r. Calculate the solution for r = 1.

Exercise 5.5: Find roots in a polynomial

I MatLab you will find a function, roots, who can calculate the roots of a polynomial. The

argument for this function is an array of coefficients in falling order of the variable.

a) Use help to figure out how to use the functions roots and poly.

b) Make a script file to solve the equation: x5 - 2x

4 + 2x

3 + 3x

2 + x + 4 = 0, using roots and

controlling the solution using poly.

47

Page 65: DSP Unit 6

c) Edit the file from prob. b), thus making it generate a plot of the placement of the roots in a

(x,y)-coordinate system

Exercise 5.6: The basic programming

a) Use the “for” command to print “hello” 5 times.

b) Use the “while” command to print “hello” 5 times.

c) Use an "if" statement to define a function which is equal to -1 if its argument is negative

and is equal to 1 if its argument is greater than or equal to 0.

Exercise 5.7:The Factorial function

Write a function factorial, able of calculating n! for any integer n. Input to the file must be the

integer n and output must be n!. You will probably need either a for or a while loop in order

to carry out the calculations. Use the online help to figure out how to use the two functions.

Note! MatLab has a built-in function prod, do not use this function in your solution.

Exercise 5.8: Calculating the cross product

a) Write a function file crossprod able to calculate the cross product between the two

vectors u and v, given by u = (u1,u2,u3), v = (v1,v2,v3) and u x v = (u2v3-v2u3,u3v1-v3u1,u1v2-

v1u2).

b) Control your function by calculating the cross product between two unity vectors.

Note! MatLab has a built-in function cross, do not use this function in your solution.

Exercise 5.9: Sum of a geometric series

Write a function able to calculate the sum of the geometric series 1+ r + r2

+ r3

+...+ rn for a

given r and n. Input to the function must be r and n and output the sum of the series.

48

Page 66: DSP Unit 6

Suggested Solution to Exercises in Chapter 5

Commands

Exercise 5.1

% This program add 2 and 5

a = 2

b = 5

c = a+b

Results

Exercise 5.1

>> Add2and5

a =

2

b =

5

c =

7

Exercise 5.2 a)

function z = Adder(x,y)

% Adder: Adder creates the sum of

the input arguments

%

% Synopsis: Z = Adder(x,y)

%

% Input: x, y = input matrices

% Note: x and y must be

the same size

%

% Output: z = x + y

z = x + y;

b)

function [C,D] = multiplier(A,B)

% multiplier: multiplies matrices A

and B

% Synopsis: [C,D] = multiplier(A,B)

% Input: A, B = input matrices

% Note: an error will occur with

either C or D unless A and

%B are square and the same size

%

% Output: C = A*B

% D = A.*B

C = A*B;

D = A.*B;

Exercise 5.2 a)

>> x=[1 3];

>> y=[5 5];

>> Adder(x,y)

ans =

6 8

b) >> A = ones(2)

A =

1 1

1 1

>> B = [1 2 ; 3 4]

B =

1 2

3 4

>> [C,D]=multiplier(A,B)

C =

4 6

4 6

D =

1 2

3 4 c)

function y = f(x)

% f: A function to experiment with

function m-files

%

% Synopsis: y = f(x)

c)We need to test this function to make sure it works as

expected >> f(2)

ans =

-2

>> x=[1 2];

49

Page 67: DSP Unit 6

%

% Input: x = input value or matrix

%

% Output: y = x.^2 - 2.*x - 2

y = x.^2 - 2.*x - 2;

>> y=f(x)

y =

-3 -2 % Now let plot the function

>> x = [-2:0.1:2];

>> y = f(x);

>> plot(x,y)

>> xlabel('x')

>> ylabel('f(x)')

Exercise 5.3 a) Create a script file “workScrip.m” force = [400, 550, 700, 500, 600];

distance = [2, 0.5, 0.75, 1.5, 3];

work = force.*distance

totalWork = sum(work)

b) create a Function

function [work, totalWork] =

WorkFunction

force = [400, 550, 700, 500, 600];

distance = [2, 0.5, 0.75, 1.5, 3];

work = force.*distance;

totalWork = sum(work);

Exercise 5.3 >> WorkScript

work =

800 275 525 750 800

totalWork =

4150

b)

>> [work, totalWork]=WorkFunction

work =

800 275 525 750 1800

totalWork =

4150

Exercise 5.4

Your script file might look like this:

% solvex - A script file solving a system of

equations

% Solves the system:

% 5*x1 + 2r*x2 + r*x3 = 2

% 3*x1 + 6*x2 + (2r-1)*x3 = 3

% 2*x1 + (r-1)*x2 + 3r*x3 = 5

% NOTICE: The value r must be defined in

workspace before running this file

A=[5 2*r r; 3 6 2*r-1; 2 r-1 3*r]; % create

coefficient matrix

b=[2;3;5]; % create result vector

det_A=det(A) % find and print determinant

x=A\b % find and print the x-vector

Exercise 5.4

» r=1;

» solvex

det_A =

64

x =

-0.0312

0.2344

1.6875

50

Page 68: DSP Unit 6

Exercise 5.5

b.

Your script file might look like this:

% solvpoly - find roots in a polynomial

% Find roots in the polynomial:

% x^5-2*x^4+2*x^3+3*x^2+x+4=0

c = [1 -2 2 3 1 4] % create array with the

coefficients

solution = roots(c) % find and print the

solution

poly(solution) % reversal calculation and

print the coefficients

c.

Insert these commands in the end of your

script file:

% generate plot

plot(solution,'o')

grid on

Exercise 5.5

b.

» solvpoly

c =

1 -2 2 3 1 4

solution =

1.5336 + 1.4377i

1.5336 - 1.4377i

-1.0638

-0.0017 + 0.9225i

-0.0017 - 0.9225i

ans =

1.0000 -2.0000 2.0000 3.0000 1.0000 4.0000

c.

Exercise 5.6

a)

for i=1:5

disp('hello')

end

b) i=1; while i<=5

disp('hello')

i=i+1;

end

c) function y = MySign(x)

% MySign: This function returns

-1 if x < 0 and 1 if x >= 0.

% Synopsis: y = MySign(x)

% Input: x = independent

variable

% Output: y = -1 if x < 0 and 1

if x >= 0

if x < 0

a)

hello

hello

hello

hello

hello

b) same as (a)

51

Page 69: DSP Unit 6

52

y=-1;

else

y=1;

end

Exercise 5.7

Your function file could look like this: function factn = factorial(n);

% FACTORIAL : function calculating n!

% Syntax : factn = factorial(n);

factn = 1; % initialize, i.e. 0!=1

for k =n:-1:1 % from n to 1

factn = factn*k; % multiply

end

Exercise 5.8

Your function file could look like this:

function w = crossprod(u,v);

% CROSSPROD : calculate cross product

of u and v

% Syntax : w = crossprod(u,v);

if length(u)>3 | length(v)>3 % check

dimensions

error('Error in vector dimensions')

end

w = [u(2)*v(3)-u(3)*v(2);

u(3)*v(1)-u(1)*v(3);

u(1)*v(2)-u(2)*v(1)];

Exercise 5.9

Your function file could look like this:

function s = gseriessum(r,n);

% GSERIESSUM : calculates sum of

geometric series

% Syntax : s = gseriessum(r,n);

nvector =0:n; % create vector from 0

to n

series = r.^nvector; % create vector

with the series

s = sum(series); % calculate the sum

Page 70: DSP Unit 6
Page 71: DSP Unit 6

Unit 6

INTRODUCTION TO DSP

WITH MATLAB

Page 72: DSP Unit 6
Page 73: DSP Unit 6

Digital Signal Processing Laboratory

Unit 6: Introduction to Digital Signal Processing with MATLAB

Introductions

We begin with the concepts of signals and systems in discrete time. A number of important

types of signals and their operations are introduced. Linear and shift-invariant systems are

discussed mostly because they are easier to analyze and implement. The convolution

representation is given special attention because of their importance in digital signal

processing and in MATLAB.

A)

DISCRETE-TIME SIGNALS

Signals are broadly classified into analog and discrete signals. An analog signal will be

denoted by xa(t), in which the variable t can represent any physical quantity, but we will

assume that it represents time in seconds. A discrete signal will be denoted by x(n), in which

the variable n is integer valued and represents discrete instances in time. Therefore it is also

called a discrete-time signal, which is a number sequence and will be denoted by one of the

following notations:

x(n)= {x(n)}= {......, x(-1), x(0), x(1),......}

where the up-arrow indicates the sample at n = 0.

In MATLAB we can represent a finite-duration sequence by a row vector of appropriate

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

For example, a sequence x(n) = {2, 1, -1,0,1,4,3, 7} can be represented in MATLAB by

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

Generally, we will use the x-vector representation alone when the sample position

information is not required or when such information is trivial (e.g. when the sequence

begins at n = 0). An arbitrary infinite-duration sequence cannot be represented in MATLAB

due to the finite memory limitations

B) TYPES OF SEQUENCES

We use several elementary sequences in digital signal processing for analysis purposes. Their

definitions and MATLAB representations are given below.

1. Unit sample sequence:

!,........0,0,0,1,0,0.....,0,0

0,1)( "

#$

#%&

'

""

n

nn(

In MATLAB the function zeros (1, N) generates a row vector of N zeros, which can be used

to implement 8(n) over a finite interval. However, the logical relation n==0 is an elegant way

of implementing 8(n). For example, to implement

53

Page 74: DSP Unit 6

#$

#%&

'

"")

o

o

onn

nnnn

,0

,1)((

over the n1 * no * n2 interval, we will use the following MATLAB function. function [x,n] = impseq(n0,n1,n2) % Generates x(n) = delta(n-n0); n1 <= n,n0 <= n2 % ---------------------------------------------- % [x,n] = impseq(n0,n1,n2) % if ((n0 < n1) | (n0 > n2) | (n1 > n2)) error('arguments must satisfy n1 <= n0 <= n2') end n = [n1:n2]; %x = [zeros(1,(n0-n1)), 1, zeros(1,(n2-n0))]; x = [(n-n0) == 0];

2. Unit step sequence:

u !,........1,1,1,1,1,0,0.....,0,0

0,1)( "

#$

#%&

+

,"

n

nn

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 #$

#%&

+

,")

o

o

onn

nnnn

,0

,1)(

over the n1 * no * n2 interval, we will use the following MATLAB function. function [x,n] = stepseq(n0,n1,n2) % Generates x(n) = u(n-n0); n1 <= n,n0 <= n2 % ------------------------------------------ % [x,n] = stepseq(n0,n1,n2) % if ((n0 < n1) | (n0 > n2) | (n1 > n2)) error('arguments must satisfy n1 <= n0 <= n2') end n = [n1:n2]; %x = [zeros(1,(n0-n1)), ones(1,(n2-n0+1))]; x = [(n-n0) >= 0];

3. Real-valued exponential sequence:

Raanx n -" ,)(

In MATLAB an array operator “ .^ ” is required to implement a real exponential sequence.

To generate x(n) = (0.9) n, 0 * n * 10, we will need the following MATLAB script:

» n = [0:10]; x = (0.9).^n;

54

Page 75: DSP Unit 6

4. Complex-valued exponential sequence:

nj

enx)( 0)(

! "#

where ! is called an attenuation and 0 is the frequency in radians. A MATLAB function

exp is used to generate exponential sequences. For example, to generate x(n) = exp [(2 + j3)

n] , 0 $ n $ 10, we will need the following MATLAB script: » n=[0:10]; x=exp((2+3j)*n);

5. Sinusoidal sequence:

x(n) = cos ( 0n +%)

where % is the phase in radians. A MATLAB function cos or sin is used to generate

sinusoidal sequences. For example, to generate x(n) = 3 cos (0.l1&n +& /3) + 2 sin (0.5&n), 0

$ n $ 10, we will need the following MATLAB script: » n = [0:10]; x = 3*cos(0.1*pi*n+pi/3) + 2*sin(0.5*pi*n);

6. Random sequences: Many practical sequences cannot be described by mathematical expressions like those above.

These sequences are called random (or stochastic) sequences and are characterized by

parameters of the associated probability density functions or their statistical moments. In

MATLAB two types of (pseudo-) random sequences are available. The rand(1,N) generates

a length N random sequence whose elements are uniformly distributed between [0,1]. The

randn(1,N) generates a length N Gaussian random sequence with mean 0 and variance 1.

Other random sequences can be generated using transformations of the above functions.

7. Periodic sequence: A sequence x(n) is periodic if x(n) = x(n+N). The smallest integer N that satisfies the above

relation is called the fundamental period. We will use to denote a periodic sequence. To

generate P periods of from one period {x(n), 0 $ n $ N -I}, we use the following: First

we generate a matrix containing P rows of x (n) values. Then we can concatenate P rows into

a long row vector using the construct (:). However, this construct works only on columns.

Hence we will have to use the matrix transposition operator' to provide the same effect on

rows.

)(~

nx

)(~

nx

» xtilde = x' * ones(l,P); % P columns of Xi x is a row vector » xtilde = xtilde(:); % long column vector » xtilde = xtilde'; % long row vector

C) OPERATIONS OF SEQUENCES

Here we briefly describe 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)}

55

Page 76: DSP Unit 6

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 x1(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. function [y,n] = sigadd(x1,n1,x2,n2) % implements y(n) = x1(n)+x2(n) % ----------------------------- % [y,n] = sigadd(x1,n1,x2,n2) % y = sum sequence over n, which includes n1 and n2 % x1 = first sequence over n1 % x2 = second sequence over n2 (n2 can be different from n1) % n = min(min(n1),min(n2)):max(max(n1),max(n2)); % duration of y(n) y1 = zeros(1,length(n)); y2 = y1; %initialization y1(find((n>=min(n1))&(n<=max(n1))==1))=x1; % x1 with duration of y y2(find((n>=min(n2))&(n<=max(n2))==1))=x2; % x2 with duration of y y = 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. A sigmult function is developed, similar

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

3. Scaling: In this operation each sample is multiplied by a scalar '.

'{x(n)} = {'x(n)}

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

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

a shifted sequence y(n).

56

Page 77: DSP Unit 6

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

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

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

Hence this operation has no effect on the vector x, but the vector n is changed by adding k to

each element. This is shown in the function sigshift. function [y,n] = sigshift(x,m,n0) % implements y(n) = x(n-n0) % ------------------------- % [y,n] = sigshift(x,m,n0) % n = m+n0; y = x;

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

folded sequence y(n).

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

In MATLAB this operation is implemented by fliplr(x)function for sample values and by -

fliplr(n) function for sample positions as shown in the sigfold function. function [y,n] = sigfold(x,n) % implements y(n) = x(-n) % ----------------------- % [y,n] = sigfold(x,n) % y = fliplr(x); n = -fliplr(n);

6. Sample summation: This operation differs from signal addition operation. It adds

all sample values of x(n)

between nl and n2.

)(............)()( 21

2

1

nxnxnxn

nn

"#(#

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 nl and n2.

) )(.........)()( 21

2

1

nxnxnxn

n

**#

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

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

((+

+,

+

+,

##2

)()(*)( nxnxnxx-

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

57

Page 78: DSP Unit 6

duration sequence x( n) can be computed in MATLAB using » Ex = sum(x .*conj(x)); % one approach » Ex = sum(abs(x).^ 2); % another approach

9. Signal power: The average power of a periodic sequence with fundamental period

N is given by

(,

#1

0

2)(

1 N

x nxN

.

EXAMPLES

6.1) Generate and plot each of the following sequences over the indicated interval.

a. x(n) = 2/(n + 2) , /(n , 4), ,5 $ n $ 5.

b. x(n) = n [u(n) , u(n , 10)] + l0e ,0.3(n,10)

[u(n , 10) , u(n , 20)] , 0 $ n $ 20.

c. x(n) = cos(0.04&n) + 0.2 (n), 0 $ n $ 50, where (n) is a Gaussian random

sequence with zero mean and unit variance.

d. x(n)={...,5,4,3,2,1,5,4,3,2,1,5,4,3,2,1,...}; ,10 $ n $ 9.

Solutions

figure(1); clf % a) x(n) = 2*delta(n+2) - delta(n-4), -5<=n<=5 n = [-5:5]; x = 2*impseq(-2,-5,5)-impseq(4,-5,5); subplot(2,2,1); stem(n,x); title('Sequence in Example 6.1a') xlabel('n'); ylabel('x(n)'); axis([-5,5,-2,3]) % % b) x(n) = n[u(n)-u(n-10)]+10*exp(-0.3(n-10))(u(n-10)-u(n-20)); 0<=n<=20 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,2,2);stem(n,x); title('Sequence in Example 6.1b') xlabel('n');ylabel('x(n)');axis([0,20,-1,11]) % % c) x(n) = cos(0.04*pi*n) + 0.2*w(n); 0<=n<=50, w(n): Gaussian (0,1) n = [0:50]; x = cos(0.04*pi*n)+0.2*randn(size(n)); subplot(2,2,3);stem(n,x);title('Sequence in Example 6.1c') xlabel('n');ylabel('x(n)');axis([0,50,-1.4,1.4]) % % d) x(n) = {...,5,4,3,2,1,5,4,3,2,1,...}; -10<=n<=9; % NOTE that the x(n) has an interval of 4 periods ! n=[-10:9]; x=[5,4,3,2,1]; xtilde=x' * ones(1,4); xtilde=(xtilde(:))'; subplot(2,2,4);stem(n,xtilde);title('Sequence in Example 6.1d') xlabel('n');ylabel('xtilde(n)');axis([-10,9,-1,6])

58

Page 79: DSP Unit 6

-5 0 5-2

-1

0

1

2

3Sequence in Example 6.1a

n

x(n

)

0 5 10 15 20

0

2

4

6

8

10

Sequence in Example 6.1b

n

x(n

)

0 10 20 30 40 50

-1

-0.5

0

0.5

1

Sequence in Example 6.1c

n

x(n

)

-10 -5 0 5

0

2

4

6Sequence in Example 6.1d

n

xtild

e(n

)

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

Solutions

figure(1); clf % The sequence x(n) is non-zero over –2 <= n <= 10 n = -2:10; x = [1:7,6:-1:1]; % generate x(n) % a) x1(n) = 2*x(n-5) - 3*x(n+4) % The first part is obtained by shifting x(n) by 5 and second part by –4 % Done by functions sigshift and sigadd [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 Example 6.2a') xlabel('n'); ylabel('x1(n)'); axis([min(n1)-1,max(n1)+1,min(x1) 1,max(x1)+1]) set(gca,'XTickMode','manual','XTick',[min(n1),0,max(n1)]) % % b) x2(n) = x(3-n) + x(n)*x(n-2) % The first term -> x(-(n-3)) by folding x(n) and shifting result by 3 % Operations are done by sigfold and sigmult

59

Page 80: DSP Unit 6

[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 Example 6.2b') xlabel('n'); ylabel('x2(n)'); axis([min(n2)-1,max(n2)+1,0,40]) set(gca,'XTickMode','manual','XTick',[min(n2),0,max(n2)])

-6 0 15

-20

-10

0

10

Sequence in Example 6.2a

n

x1(n

)

-7 0 120

10

20

30

40Sequence in Example 6.2b

x2(n

)

n

6.3) Generate the complex-valued signal

x(n) = e(,0.1+j0.3)n

, ,l0 $ n $ l0

and plot its magnitude, phase, the real part, and the imaginary part in four separate subplots.

Solution

figure(1); clf % a) x(n) = exp((-0.1+j0.3)n), -10 <= n <= 10; n = [-10:1:10]; alpha = -0.1+0.3j; x = exp(alpha*n); subplot(2,2,1); stem(n,real(x));title('real part');xlabel('n') subplot(2,2,2); stem(n,imag(x));title('imaginary part');xlabel('n') subplot(2,2,3); stem(n,abs(x));title('magnitude part');xlabel('n') subplot(2,2,4); stem(n,(180/pi)*angle(x));title('phase part');xlabel('n')

60

Page 81: DSP Unit 6

-10 -5 0 5 10-3

-2

-1

0

1

2real part

n

-10 -5 0 5 10-2

-1

0

1imaginary part

n

-10 -5 0 5 100

1

2

3magnitude part

n

-10 -5 0 5 10-200

-100

0

100

200phase part

n

D) CONVOLUTION

Convolution can be evaluated in many different ways. If the sequences are mathematical

functions (of finite or infinite duration), then we can analytically evaluate the linear

convolution sum equation , y(n) = x(n) * h(n) for all n to obtain a functional form of y(n). If

arbitrary sequences are of infinite duration, then MATLAB cannot be used directly to

compute the convolution. MATLAB does provide a built-in function called conv that

computes the convolution between two finite duration sequences. The conv function assumes

that the two sequences begin at n = 0 and is invoked by

» y = conv(x,h);

to obtain the correct y(n) values. However, the conv function neither provides nor accepts any

timing information if the sequences have arbitrary support. What is needed is a beginning

point and an end point of y(n). Given finite duration x(n) and h(n), it is easy to determine

these points. Let

{ x(n); nxb $ n $ nxe } and { h (n); hhb $ n $ hhe }

61

Page 82: DSP Unit 6

be two finite-duration sequences. Then we will observe that the beginning and end points of

y(n) are

nyb = nxb + nhb and nye = nxe + nhe

respectively. A simple extension of the conv function, called conv_m, which performs the

convolution of arbitrary support sequences can now be designed. function [y,ny] = conv_m(x,nx,h,nh) % Modified convolution routine for signal processing % -------------------------------------------------- % [y,ny] = conv_m(x,nx,h,nh) % y = convolution result % ny = support of y % x = first signal on support nx % nx = support of x % h = second signal on support nh % nh = support of h % nyb = nx(1)+nh(1); nye = nx(length(x)) + nh(length(h)); ny = [nyb:nye]; y = conv(x,h);

Examples

6.4) Given the following two sequences

x(n) = [3, 11, 7, 0, 1, 4, 2], 3 ! n ! 3; h( n) = [2, 3, 0, 5, 2, 1] , 1 ! n ! 4

determine the convolution y(n) = x(n) * h(n).

Solution

% Using built-in conv function

» x = [3, 11,7,0, -1, 4, 2];

» h = [2, 3, 0, -5, 2, 1];

» y = conv(x,h)

y =

6 31 47 6 -51 -5 41 18 -22 -3 8 2

% Using conv_m, modified from conv function % x(n)=[3,11,7,0,-1,4,2]; nx = [-3:3] % h(n)=[2,3,0,-5,2,1]; nh = [-1:4] % y(n)=conv(x,h)

» x = [3, 11, 7, 0, -1, 4, 2]; nx = [-3: 3];

» h = [2, 3, 0, -5, 2, 1]; nh = [-1: 4];

» y] = conv_m(x,nx,h,nh) [y,n y =

6 31 47 6 -51 -5 41 18 -22 -3 8 2

ny =

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

Therefore, y(n) = [6, 31, 47, 6, -51, -5, 41, 18, -22, -3, 8, 2]

62

Page 83: DSP Unit 6

Lab 2

LTI DISCRETE –TIME SYSTEMS,

CONVOLUTION AND DIFFERENCE

EQUATIONS

Page 84: DSP Unit 6
Page 85: DSP Unit 6

Digital Signal Processing Laboratory

LTI Discrete-Time System, Convolution

And

Difference Equations

Overview

In this lab, we will use MATLAB to explore the following topics

! Basic MATLAB Commands and Sequence Generation

! LTI Discrete-Time System and Convolution

! Time-Domain Difference Equations

Section 1 : Basic MATLAB Commands and Sequence Generation

Unit Sample Sequence

The (shifted) unit sample sequence (unit impulse) is defined as

"#$

%

&&'

0

0

00

1][

nn

nnnn(

To create an impulse in MATLAB, we must decide how much of the signal is of interest. If the

impulse ][n( is going to be used to drive a causal linear time-invariant (LTI) system, we might

want to see the L points from n = 0 to n = L-1. The following is a sample command to create

the impulse:

L = 31;

n = 0 : (L-1);

delta = [1 zeros(1, L-1)];

stem(n, delta);

Note that MATLAB indexing scheme starts with 1, hence delta(1) = 1 and delta(0) is not

defined.

Exponential Sequence

A general form of an exponential sequence is given by

nKanx &][

where K and a are real or complex numbers. The following commands show how to generate a

real exponential sequence nnx )9.0(2][ &K = 2;

a = 0.9;

1

Page 86: DSP Unit 6

n = 0:20;

x = K*a.^n;

stem(n, x);

Note that we preceded the power operator with a period to indicate an array power rather than a

matrix power.

Sinusoidal Sequence

For sinusoidal sequence, the general form is given by

)cos(][ )* +& nAns f,* 2&

If a sinusoidal sequence is sampled from a continuos time signal s(t) with sampling interval T,

the relationship between s[n] and s(t) is given by

nTttsns

&& )(][

In MATLAB, functions like cos() and sin() accept angles in radians. By defining an indexing

sequence n=0:20 for example, we can generate a sinusoidal sequence with angular frequency

0.25, simply by keying )25.0cos( ns ,& .

Exercise 1.1

1. Generate and plot the following sequences. The horizontal (n) axis should extend only over

the range indicated and should be labeled accordingly. Use the command stem to display the

sequence.

(a) x ]4[5.01 '& n( 100 -- n

(b) ]3[22 +& nx ( 1010 --' n

2. Enter the following commands to the MATLAB command prompt.

x = [0 1 2 1 0 0];

x = x’;

y = ones(1, 4);

z = x * y;

z = z(:);

size(z);

n=0:length(z)-1;

stem(n, z);

(a) How do you relate the sequence x to z?

(b) What is the period of z? How many periods are displayed?

(c) Using the above example, you would be able to get the idea of how to construct a

periodic sequence. Generate and plot (using stem) a periodic impulse train with period

4, length 40. In the plot, start the signal at n = 0.

2

Page 87: DSP Unit 6

Exercise 1.2

1. Generate the following exponential sequence. For complex sequence, plot the real and

imaginary parts separately. You may look at the command subplot for instruction on

plotting several figures in one display window.

(a) nnx )5.1(3.0][ & 300 -- n

(b) njenx )5.02.0(][ +'& 400 -- n

Exercise 1.3

1. Given a 4Hz continuous time sinusoidal signal s )8cos()(1 tt ,& . Using sufficient points,

plot the signal for duration of 2 seconds. (In MATLAB, the signals are all discrete time but

we could approximate a continuous time signal by having a high sampling rate and use the

command plot to plot the interpolated version of it).

2. With a sampling time of T = 0.1sec, generate 20 samples (which is 2 seconds) of the

sampled signal of s1(t). Plot the sequence (using stem), using time as the axis rather than the

index n (t=0, 0.1, 0.2, ...).

3. Repeat the above but with the following sinusoidal function )12cos()(2 tts ,& and

)28cos()(3 tts ,& .

4. Compare the three sampled signals, are they the same?

5. Explain the above observation.

Section 2 : LTI Discrete-Time System and Convolution

A consequence of the linear, time-invariant property is that an LTI discrete-time system1 is

completely specified by its impulse response. If we know h[n], the impulse response of a

system, we can compute the output of the system to any arbitrary input, x[n]. The relationship is

represented mathematically as the convolution sum of the sequences x[n] and h[n]

!

!"

!

!"

"#"# ][][][][][ knhkxkhknxny

The above equation can be written compactly as ][][][ nhnxny $# . Although the summation is

from to , for practical sequences, we have finite lengths and hence the resulting output

sequences will be finite length too. In MATLAB, the convolution operation is performed using

the command conv.

!" !

Exercise 2.1

1. In this exercise, we will explore the convolution operation.

(a) Write a MATLAB function to generate a square-wave form (alternating between an

amplitude of 0 and A) of length L samples, period T samples, and on for S samples per

period.

1 For our purpose, System is meant to be LTI Discrete-Time System.

3

Page 88: DSP Unit 6

(b) Create a square wave sq of length 60, period 10, and amplitude 2, and is on for 4

samples per period. Create a vector of length 1 representing an impulse ( d1 = [1]; ).

(c) Perform the convolution of sq and d1 using the conv and plot the resulting sequence.

(d) Create another vector representing an impulse but of length 10 ( d2 = [1 zeros(1, 9)]; ).

Convolute d2 with sq and plot the result. Explain any difference that you observe. If the

lengths of the two sequences being convoluted are M and N, what is the length of the

resulting sequence after convolution?

2. Generate 50 samples of a discrete-time cosine wave

)3/125.0cos(5][ %% &# nnx , 490 '' n .

(a) Given the following system

])1[][(3][ ""# nxnxny

What is the impulse response h of the system? Compute the output y of the system with

input sequence x. This system is called the first difference system.

(b) Plot the first 50 samples of both waveform x and y on the same figure, using subplot

(note that length of y and x are not the same).

(c) From the plot, with the exception of the first sample y[0], the sequence y seems to be a

scaled and shifted cosine wave of the same frequency as the input x. Explain why the

first sample is different from the others.

(d) Determine the frequency, amplitude and phase of y directly from the plot. Ignore the

first output point, y[0].

(e) Compute the relative amplitude and phase, i.e., the ratio of output to input amplitudes

and the difference of output and input phase.

(f) Derive the mathematical expression for the output when the input sequence is a complex

exponential . From this formula, determine how much the amplitude and

phase should change for x[n] which has a frequency

njenx (#][

%( 125.0# .

3. In this exercise, we will examine the linearity property of the LTI Discrete-Time System.

For all the sequences to be generated, make sure that you have the first 50 samples.

(a) Multiply the sequence x from question (2) by two to get x1 = 2*x. Generate the signal y1

as the output of the first difference system with input x1. Repeat the relative amplitude

and phase measurements described in question (2).

(b) Generate a new sequence x2 corresponding to the discrete-time signal

)25.0cos(4][2 nnx %#

Compute y2, the output of the first difference system with input x2. Then repeat the

relative amplitude and phase measurement as before. Observe how the amplitude, phase

and frequency of y2 change compare to the input.

(c) Obtain x3 that is the sum of x1 and x2. Compute y3, the output of first difference system

with the input x3. Plot y1+ y2 and y3. Are they equal?

4

Page 89: DSP Unit 6

4. In this exercise, we will examine the time-invariant property of the LTI Discrete-Time

System. Time-shift the input x by 3 time units to get

)3/)3(125.0cos(5][4 %% &"# nnx 490 '' n

and then compute the output y4 of the first difference system with input x4. Compare y4 to

y. Explain any differences that you observe.

5. Complicated systems are often made up from simple building blocks. In the system below,

a unit delay system is cascaded with a FIR filter (which is the first difference system as

above).

w[n]x[n] w[n] = x[n-1] y[n] = w[n] - w[n-1]

y[n]

Figure 1 Cascaded System

Given an input sequence x[n] = [ 1 2 3 4 5 5 4 3 2 1], compute the output of the system y[n].

Reverse the order of the system and compute the new output. Are they the same?

We will use the function filter to implement a more complex cascade system in section 3.

Section 3 : Time-Domain Response of Difference Equations

Of particular importance in digital signal processing is the class of systems that can be

represented by linear constant-coefficient equations. In this section, you will generate the

response of an IIR (infinite impulse response) filter, which is a linear time-invariant (LTI)

system expressed as a linear constant-coefficient equation:

##

"#"M

l

l

N

k

k lnxbknya00

][][

...(1)

In MATLAB, difference equations are represented by two vectors: one vector containing the

feed forward coefficients, bl, for the x terms, and the other vector containing the feedback

coefficients, ak, for the y terms. The coefficient a0 is usually taken to be 1, so that when y[n] is

written in terms of past values it drops out:

##

"&""#M

l

l

N

k

k lnxbknyaa

ny010

][][1

][

...{2)

5

Page 90: DSP Unit 6

In MATLAB, the filter function will divide out a0, so it must not be zero.

The function y = filter (b, a, x) implements a digital filter defined by the a and b coefficient

vectors as in Equation (1) to filter the data stored in x. If x is the unit impulse signal, then y will

be the impulse response h[n] for a filter specified by vector a and b. Note that the function filter

returns only as many samples into y as there are in x (i.e. the impulse response is truncated to

the length of the unit impulse vector, x).

Exercise 3.1

1. Create vectors a and b that contain the coefficient of x[n] and y[n], respectively, in the

following difference equation:

]2[3.0]1[6.0][3.0]2[9.0][ "&"&#"& nxnxnxnyny

...(3)

2. Calculate y[n] analytically for x[n] = ][n) .

3. Now create a unit impulse vector of length 128. Generate the first 128 points of the impulse

response of the filter in Equation (3). Use stem to plot these values as a discrete-time signal

versus time. It may help to plot just the first 10 or 20 points.

Exercise 3.2

1. Use the filter function to generate and plot the impulse response h[n] of the following

difference equation. Plot h[n] in the range of –10 ' n ' 100.

]1[2

1][]2[8.0]1[)

16cos(8.1][ "&#"&"" nxnxnynyny

%

...(4)

2. Determine the impulse response analytically and confirm your results.

Exercise 3.3

1. The general moving-average system is defined as

"#

"&&

#2

1

][1

1][

21

M

Mk

knxMM

ny

...(4)

For a causal system, M1 = 0. The equation can the be written as

#

"&

#2

02

][)1(

1][

M

k

knxM

ny

...(5)

6

Page 91: DSP Unit 6

which is of the same form as (1). The impulse response can be determined as

*+

*,- ''

&#otherwise

MnMnh

0

01

1

][ 2

2

...(6)

which can be expressed as a convolution operation

][*])1[][()1(

1][ 2

2

nMnnM

nh .)) """&

#

...(7)

(a) Given x[n] = [3 3 4 2 5 3 4 5 1 4 0 0], and with M2 = 2 for a 3-points moving-

average system. Use filter to compute the output of the system with x[n].

(b) Equation (7) suggests that the causal moving-average system can be represented as

the cascade system consists of an attenuator, a (M2 + 1)-th difference system and an

accumulator as shown in Figure 2.

)1(

1

2 &M

w[n] x1[n] y[n]x[n] Accumulator

system -

+

+

(M2 + 1)

sample delay

Attenuator

Figure 2 Block diagram of the moving-average system

The output of the accumulator system satisfies the difference equation

y[n]-y[n-1] = x1[n].

With x[n] as the input, compute the output of attenuator, w[n]. Feed w[n] to the

difference system to get the output x1[n]. Finally, compute the output of the system y[n],

using x1[n] as the input to the accumulator system.

Write a difference equation for the above system. You should be able to get a different

form from (5). Compute the output using this difference equation for x[n] with the filter

function.

7

Page 92: DSP Unit 6

Proposed Sample Solution

Exercise 1.1

1. The following scripts will generate the required plots

%basic sequence'

%exercise 1.1

%question 1 (a)

n=0:10;

x1=[zeros(1, length(n))];

x1(5)=1;

x1=0.5*x1;

figure;

subplot(211);

stem(n, x1);

%question 1(b)

n=-10:10;

x2=[zeros(1, length(n))];

x2(8)=1;

x2=2*x2;

subplot(212);

stem(n, x2);

Figure 1.1.1 shows the plots

Figure 1.1.1

8

Page 93: DSP Unit 6

2. Observe from the plot

(a) z is a periodic sequence with x as the basic sequence for one period of z.

(b) Period = 6. 4 periods are displayed.

(c) The following scripts will generate the required plot

%periodic pulse train

x=[1 0 0 0];

x=x';

y=ones(1, 10);

z=x*y;

z=z(:);

n=0:length(z)-1;

stem(n, z);

Figure 1.1.2 shows the plot

Figure 1.1.2

Exercise 1.2

1. The following scripts will generate the required sequences and plots.

1. Scripts for (a)

n=0:30;

K=0.3;

a=1.5;

x=K*a.^n;

figure;

stem(n, x);

ylabel('x[n]=0.3(0.5).^n');

Figure 1.2.1 shows the plot.

9

Page 94: DSP Unit 6

Figure 1.2.1

The scripts for (b)

%question 1 (b)

n=0:40;

x=exp(-0.2+j*0.5).^n;

%new window

figure;

subplot(211);

stem(n, real(x));

title('Real part');

subplot(212);

stem(n, imag(x));

title('Imaginary part');

Figure 1.2.2 shows the plot.

10

Page 95: DSP Unit 6

Figure 1.2.2

Exercise 1.3

1. The following scripts will plot the required plots for step (1)-(3)

%continuous time signal plot s1=cos(8*pi*t)for 2 sec

t=0:0.01:2;

s1=cos(8*pi*t);

figure;

subplot(321);

plot(t, s1);

ylabel('s1(t)');

%sampled sequnce of s1

n=0:20;

T=0.1;

s1_s=cos(8*pi*T*n);

subplot(322);

stem(n*T,s1_s);

ylabel('s1[n])');

%continuous time signal plot s2=cos(12*pi*t)for 2 sec

s2=cos(12*pi*t);

subplot(323);

plot(t, s2);

ylabel('s2(t)');

%sampled sequnce of s2

n=0:20;

11

T=0.1;

Page 96: DSP Unit 6

s2_s=cos(12*pi*T*n);

subplot(324);

stem(n*T,s2_s);

ylabel('s2[n]');

%continuous time signal plot s3=cos(28*pi*t)for 2 sec

s3=cos(28*pi*t);

subplot(325);

plot(t, s3);

ylabel('s3(t)');

%sampled sequnce of s3

n=0:20;

T=0.1;

s3_s=cos(28*pi*T*n);

subplot(326);

stem(n*T,s3_s);

ylabel('s3[n]');

Figure 1.3.1 shows the plots

4. The three sampled signals are all the same.

5. Aliasing due to low sampling rate. The sampling rate is 10Hz, For s1, the frequency is

4Hz, for s2, the frequency is 6Hz and for s3, the frequency is 14Hz. Hence aliasing

occurs in sampled signals s2 and s3. It can be shown that all cosine waveforms of

frequencies given by Hz, with k being any nonnegative integer, lead to the

sequence

)410( k

)8. n0cos(][ns !" when sampling at 10Hz.

Figure 1.3.1

12

Page 97: DSP Unit 6

Section 2 : LTI Discrete-Time System and Convolution

Exercise 2.1

1. (a) A function to generate a square-wave sequence

function v=squarewave(A, L, T, S)

% function v=squarewave(A, L, T, S)

% A : amplitude

% L : length of sequence, or number of samples

% T : number of samples in one period

% S : number of samples which are 1

% v : return valu, sequence of squarewave

v=[A*ones(1, S) zeros(1, T-S)]'*[ones(1, L/T)];

v=v(:);

(b), (c) & (d)

The following scripts generate the sequences and the plots

sq=squarewave(2, 60, 10, 4);

d1=[1];

d2=[1 zeros(1, 9)];

y1=conv(sq, d1);

y2=conv(sq, d2);

n=0:length(sq)-1;

m=0:length(y1)-1;

k=0:length(y2)-1;

figure;

subplot(311);

stem(n, sq);

subplot(312);

stem(m, y1);

subplot(313);

stem(k, y2);

Figure 2.1.1 shows the plots.

(a) We noticed that the outputs lengths are different. y1[n] has 60 samples while

y2[n] has 70 samples. Since the sequences are causal, the first sample is at n = 0.

We can conclude that if the lengths of the two sequences being convoluted are M

and N, the length of the resulting sequence after convolution would be M+N+1.

13

Page 98: DSP Unit 6

Figure 2.1.1

2. (a) System impulse response is ])1[][(3][ ##" nnnh $$

(b) The following scripts perform the convolution and generate the plots of x and y.

figure;

n=0:49;

x=5*cos(0.125*pi*n+pi/3);

h=[3 -3];

y=conv(x, h);

%select the first 50 samples

y=y(1:50);

subplot(311);

stem(n, x);

ylabel('x');

xlabel('n');

subplot(312);

stem(n, y, 'r');

ylabel('y');

xlabel('n');

subplot(313);

stem(n, y, 'r');

14

Page 99: DSP Unit 6

hold;

stem(n, x, 'b');

xlabel('n');

Figure 2.1.2 shows the plots

Figure 2.1.2

(c) x is only defined from 0 49%% n , hence the first sample of y is obtained from the

difference of x[n] with 0.

(d) The frequency remains the same as the input.

There are 16 samples in one interval of y, thus the frequency is !!

125.016

2" .

Each sample interval represents phase angle !125.0 . By a careful examination of

the phase shift between plot of y and x, we would find that there is a shift of 3.5

samples. Hence, the phase of y is given by

!!!

48

37)125.0(

2

7

3"& .

From the plot, the amplitude of y is about 5.85.

(e) Relative amplitude = 5.85/5 = 1.17

15

Page 100: DSP Unit 6

Relative phase = !!16

7)125.0(

2

7"

(f) With x njen '"][ , ] )(3 )1( #

#"njnj ee ''[ny

Given that !' 125.0" , we have

][ny )(3 )1(125.0125.0 ##"

njnj ee !!

We would not use the first sample for comparison, instead we use the second

sample.

!! 16

9

125.0 17.1)1(3]1[j

j eey "#"

and

!! 8

1

125.0]1[j

j eex ""

From here, we can determine that the amplitude would change by a factor of 1.17

and the phase shift is !16

7, which are observed from the plots.

3. The following scripts generates the outputs and plots for (a)-(c)

figure;

x1=2*x;

y1=conv(x1, h);

y1=y1(1:50);

subplot(311);

stem(n, x1);

ylabel('x1');

xlabel('n');

subplot(312);

stem(n, y1, 'r');

ylabel('y1');

xlabel('n');

subplot(313);

stem(n, y1, 'r');

hold;

stem(n, x1, 'b');

xlabel('n');

figure;

x2=4*cos(0.25*pi*n);

y2=conv(x2, h);

y2=y2(1:50);

subplot(311);

stem(n, x2);

16

Page 101: DSP Unit 6

ylabel('x2');

xlabel('n');

subplot(312);

stem(n, y2, 'r');

ylabel('y2');

xlabel('n');

subplot(313);

stem(n, y2, 'r');

hold;

stem(n, x2, 'b');

xlabel('n');

figure;

x3=x1+x2;

y3=conv(x3, h);

y3=y3(1:50);

subplot(211);

stem(n, y3);

ylabel('y3=conv(x3, h)');

y3n=y1+y2;

y3n=y3n(1:50);

subplot(212);

stem(n, y3n);

ylabel('y3n=y1+y2');

(a) Figure 2.1.3 shows the plots of x1.

17

Page 102: DSP Unit 6

Figure 2.1.3

Comaparing y and y1, we noticed that the output y1 has been shifted by the same

number of samples(3.5 samples) as y but the amplitude is twice of y. Hence,

Relative amplitude = 11.7/5 = 2.34

Relative phase = !!16

7)125.0(

2

7"

(b) Figure 2.1.4 shows the plots of x2. The frequency remains the same as the input x2.

There is a 6.5 samples shift between x2 and y2. Hence, the relative phase is given by

!!8

13)25.0(5.6 " .

As for the relative amplitude, we could use MATLAB to calculate x2 at the mid-point

between n = 0 and n = 1. We calculate 4 ))5.0(25.0cos( ! and it is equals to 3.6955.

The sample of y2 after 6.5 samples shift would then be y2[7], which is 8.4853. The

relative amplitude is 296.26955.3

4853.8" .

18

Page 103: DSP Unit 6

Figure 2.1.4

(c) Figure 2.1.5 shows the plots of y1+y2 and y3. From the plots, we can observe that

they are equal.

19

Page 104: DSP Unit 6

Figure 2.1.5

4. The following scripts generate the outputs and plots.

figure;

x4=5*cos(0.125*pi*(n-3)+pi/3);

y4=conv(x4, h);

y4=y4(1:50);

subplot(221);

stem(n, x);

ylabel('x');

subplot(222);

stem(n, y);

ylabel('y');

subplot(223);

stem(n, x4);

ylabel('x4');

subplot(224);

stem(n, y4);

ylabel('y4');

Figure 2.1.6 shows the plots. Except the first sample, y4 is a shifted signal of y by 3

samples.

20

Page 105: DSP Unit 6

Figure 2.1.6

5. The outputs of the system are calculated using the following scripts

%Cascaded system

%impulse response for unit delay

hw=[0 1];

%impulse response for first difference system

hd=[1 -1];

x=[1 2 3 4 5 5 4 3 2 1];

w1=conv(x, hw);

y1=conv(w1, hd);

y1

y2=conv(x, hd);

w2=conv(y2, hw);

w2

A snippet of the MATLAB command windows shows the outputs

y1 =

0 1 1 1 1 1 0 -1 -1 -1 -1 -1

w2 =

0 1 1 1 1 1 0 -1 -1 -1 -1 -1

21

Page 106: DSP Unit 6

Both systems produce the same outputs, which show that the order of a cascaded

system is not of any difference to the output.

22

Page 107: DSP Unit 6

Section 3 : Time-Domain Response of Difference Equations

Exercise 3.1

1. As in the scripts .

2. Calculation of y[n] analytically:

We have calculated the first few samples and verified with the MATLAB outputs.

Since the system is causal, so ,0,0][ (" nny and the input is an impulse ][][ nnx $" .

3.0]0[

]2[3.0]1[6.0]0[3.0]2[9.0]0[

0

"

#&#&"#&

"

y

xxxyy

n

6.0]1[

]1[3.0]0[6.0]1[3.0]1[9.0]1[

1

"

#&&"#&

"

y

xxxyy

n

03.0]2[

]0[3.0]1[6.0]2[3.0]0[9.0]2[

2

"

&&"&

"

y

xxxyy

n

54.0]3[

]1[3.0]2[6.0]3[3.0]1[9.0]3[

3

#"

&&"&

"

y

xxxyy

n

027.0]4[

]2[3.0]3[6.0]4[3.0]2[9.0]4[

4

#"

&&"&

"

y

xxxyy

n

486.0]5[

]3[3.0]4[6.0]5[3.0]3[9.0]5[

5

#"

&&"&

"

y

xxxyy

n

and so on...

3. The following scripts generate the impulse response of the filter

%exercise 3.1

%filter coefficients

a=[1 0 0.9];

b=[0.3 0.6 0.3];

%impulse

x=[1 zeros(1, 127)];

%filter impulse response

23

y=filter(b, a, x);

Page 108: DSP Unit 6

%get the first 20 samples

y1=y(1:20);

figure;

subplot(311);

stem(0:length(x)-1, x);

ylabel('d[n]');

subplot(312);

stem(0:length(y)-1, y);

ylabel('y');

subplot(313);

stem(0:length(y1)-1, y1);

ylabel('y1');

Figure 3.1.1 shows a plot of the impulse response of the filter.

Figure 3.1.1

The calculated y[n] is verified with the MATLAB outputs

>>y1

y1 =

Columns 1 through 7

0.3000 0.6000 0.0300 -0.5400 -0.0270 0.4860 0.0243

Columns 8 through 14

-0.4374 -0.0219 0.3937 0.0197 -0.3543 -0.0177 0.3189

Columns 15 through 20

24

0.0159 -0.2870 -0.0143 0.2583 0.0129 -0.2325

Page 109: DSP Unit 6

Exercise 3.2

1. The following scripts generate the filter impulse response from 10010 %%# n .

a=[1 -1.8*cos(pi/16) 0.8];

b=[1 0.5];

x=[zeros(1, 10) 1 zeros(1, 100)];

y=filter(b, a, x);

figure;

subplot(211);

stem(-10:100, x);

ylabel('x[n]');

axis([-10 100 -5 5]);

subplot(212);

stem(-10:length(y)-11, y);

ylabel('y[n]');

axis([-10 100 -5 5]);

y1=y(1:20);

y1

The first 20 samples of the filter impulse response as calculated by MATLAB

>>y1

y1 =

Columns 1 through 7

0 0 0 0 0 0 0

Columns 8 through 14

0 0 0 1.0000 2.2654 3.1994 3.8359

Columns 15 through 20

4.2125 4.3680 4.3414 4.1699 3.8885 3.5289

Figure 3.2.1 shows the filter impulse response from 10010 %%# n .

25

Page 110: DSP Unit 6

Figure 3.2.1

Calculation of y[n] analytically,

System is causal, so ,0,0][ (" nny and the input is an impulse ][][ nnx $" .

1]0[

]1[2

1]0[]2[8.0]1[)

16cos(8.1]0[

0

"

#&"#&##

"

y

xxyyy

n

!

2654.2]1[

]0[2

1]1[]1[8.0]0[)

16cos(8.1]1[

1

"

&"#&#

"

y

xxyyy

n

!

1994.3]2[

]1[2

1]2[]0[8.0]1[)

16cos(8.1]2[

2

"

&"&#

"

y

xxyyy

n

!

26

Page 111: DSP Unit 6

8359.3]3[

]2[2

1]3[]1[8.0]2[)

16cos(8.1]3[

3

"

&"&#

"

y

xxyyy

n

!

and so on...

The results are the same as calculated by MATLAB.

Exercise 3.3

1. The causal 3-points moving-average system can be defined as

])2[]1[][(3

1][ #&#&" nxnxnxny

(a) The following scripts calculate the output of the system with x[n]

%3 point moving average

x=[3 3 4 2 5 3 4 5 1 4 0 0];

a=[1];

b=[1/3 1/3 1/3];

y=filter(b, a, x);

x

y

A snippet from MATLAB command windows

x =

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

y =

Columns 1 through 7

1.0000 2.0000 3.3333 3.0000 3.6667 3.3333 4.0000

Columns 8 through 12

4.0000 3.3333 3.3333 1.6667 1.3333

(b) The following scripts calculate the outputs of the cascaded system as described in the

question

%part (b)

%we would use filter to calculate (although it is simpler not to use it)

%attenuater

a_att=[1];

b_att=[1/3];

w=filter(b_att, a_att, x);

w

%3-th difference system

27

Page 112: DSP Unit 6

a_diff=[1];

b_diff=[1 0 0 -1];

x1=filter(b_diff, a_diff, w);

x1

%accumulator

a_acc=[1 -1];

b_acc=[1];

yy=filter(b_acc, a_acc, x1);

yy

The outputs from MATLAB are given as below

w =

Columns 1 through 7

1.0000 1.0000 1.3333 0.6667 1.6667 1.0000 1.3333

Columns 8 through 12

1.6667 0.3333 1.3333 0 0

x1 =

Columns 1 through 7

1.0000 1.0000 1.3333 -0.3333 0.6667 -0.3333 0.6667

Columns 8 through 12

0 -0.6667 0 -1.6667 -0.3333

yy =

Columns 1 through 7

1.0000 2.0000 3.3333 3.0000 3.6667 3.3333 4.0000

Columns 8 through 12

4.0000 3.3333 3.3333 1.6667 1.3333

We can see that the outputs are the same as in (a).

Note that the accumulator system difference equation is given as

][]1[][ 1 nxnyny "##

By combining the attenuator and the (M2+1)-th difference system, we can write the

following difference equation

])1[][(1

1][ 2

2

1

!

" MnxnxM

nx

Using the two equations, we can write the moving-average system difference

equation as

])3[][(1

1]1[][

2

!

" nxnxM

nyny

The following scripts use the new difference equation to calculate the system outputs

% new different equation

a_new=[1 -1];

b_new=[1/3 0 0 -1/3];

y_new=filter(b_new, a_new, x);

y_new

28

Page 113: DSP Unit 6

29

The MATLAB outputs

y_new =

Columns 1 through 7

1.0000 2.0000 3.3333 3.0000 3.6667 3.3333 4.0000

Columns 8 through 12

4.0000 3.3333 3.3333 1.6667 1.3333

As expected, they are the same as in (a).

In fact, an unlimited number of distinct difference equations can be used to represent

a given LTI system.

Page 114: DSP Unit 6