copy of matlab (lab manuals)

31
 SIGNALS AND SYSTEMS USING MATLAB Laboratory Manual Department of Electronics & Telecommunication Engineering College of Engineering & Emerging Technologies Faculty of Engineering & Technology UNIVERSITY  OF THE PUNJAB 

Upload: masyousaf

Post on 09-Apr-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 1/31

 

SIGNALS AND SYSTEMS

USING MATLAB

Laboratory Manual

__________________________________________________________________________

Department of Electronics & Telecommunication Engineering

College of Engineering & Emerging TechnologiesFaculty of Engineering & Technology

UNIVERSITY  OF THE PUNJAB 

Page 2: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 2/31

 

TABLE OF CONTENTS:-

 No.  Title  Page

1 Basic Operations Of Matlab 2

2 Matrices 9 3 M-Files 17 

4 Signals and Systems 19 

5 System Analysis 27 

6 Fourior Analysis 28 

Textbook:

•  Signals and Systems by Alan V, Oppenheim&Alan S. Willsky with S. Hamid Nawab

Page 3: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 3/31

- 1 -

© Department of ETE, CEET, PU.

MATLAB

Matlab is a program that was originally designed to simplify the implementation of numerical linear algebra

routines. It has since grown into something much bigger, and it is used to implement numerical algorithms

for a wide range of applications. The basic language used is very similar to standard linear algebra notation.

Matlab is also best for the implementation of many applications of SIGNALS AND SYSTEMS.

Matlab's strengths include cutting-edge algorithms, enormous data handling abilities, and powerful

 programming tools. Matlab is not designed for symbolic computation, but it makes up for this weakness by

allowing the user to directly link to Maple. The interface is mostly text-based, which may be disconcerting

for some users.

The main objective of this manual is to cover some basics commands of matlab which are being used inalgebra and signals and systems.

General Information

Matlab is case sensitive so "a" and "A" are two different names.

Comment statements are preceded by a "%".

Clear, clears all variables

On-line help for MATLAB can be reached by typing help for the full menu or typing help followed by a

 particular function name or M-file name. For example, help cos gives help on the cosine function.

The number of digits displayed is not related to the accuracy. To change the format of the display, typeformat short e for scientific notation with 5 decimal places, format long e for scientific notation with 15

significant decimal places and format bank for placing two significant digits to the right of the decimal.

The commands who and whos give the names of the variables that have been defined in the workspace.

The command length(x) returns the length of a vector x and size(x) returns the dimension of the matrix x.

Page 4: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 4/31

- 2 -

© Department of ETE, CEET, PU.

1. Basic Operations Of Matlab

1.1  Vectors

Almost all of Matlab's basic commands revolve around the use of vectors. A vector is defined by placing a

sequence of numbers within square braces:

>> v = [3 1]

v =

3 1

This creates a row vector which has the label "v". The first entry in the vector is a 3 and the second entry is a

1. Note that matlab printed out a copy of the vector after you hit the enter key. If you do not want to print out

the result put a semi-colon at the end of the line:

>> v = [3 1];>>If you want to view the vector just type its label:

>> v

v =

3 1

You can define a vector of any size in this manner:

>> v = [3 1 7 -21 5 6]v =3 1 7 -21 5 6

 Notice, though, that this always creates a row vector. If you want to create a column vector you need to take

the transpose of a row vector. The transpose is defined using an apostrophe (" ' "):>> v = [3 1 7 -21 5 6]'

v =

317

-2156

A common task is to create a large vector with numbers that fit a repetitive pattern. Matlab can define a set

of numbers with a common increment using colons. For example, to define a vector whose first entry is 1,

the second entry is 2, the third is three, up to 8 you enter the following:

>> v = [1:8]

v =

1 2 3 4 5 6 7 8

Page 5: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 5/31

- 3 -

© Department of ETE, CEET, PU.

If you wish to use an increment other than one that you have to define the start number, the value of the

increment, and the last number. For example, to define a vector that starts with 2 and ends in 4 with steps of 

.25 you enter the following:

>> v = [2:.25:4]

v =

Columns 1 through 7

2.0000 2.2500 2.5000 2.7500 3.0000 3.2500 3.5000

Columns 8 through 9

3.7500 4.0000

1.1.1.  Accessing elements within a vector 

You can view individual entries in this vector. For example to view the first entry just type in the following:

>> v(1)

ans =

2

This command prints out entry 1 in the vector. Also notice that a new variable called ans has been created.

Any time you perform an action that does not include an assignment matlab will put the label ans on the

result.

To simplify the creation of large vectors, you can define a vector by specifying the first entry, an

increment, and the last entry. Matlab will automatically figure out how many entries you need and their 

values. For example, to create a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line:>> 0:2:8

ans =

0 2 4 6 8

Matlab also keeps track of the last result. In the previous example, a variable

"ans" is created. To look at the transpose of the previous result, enter the following:

>> ans'

ans =

02468

Page 6: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 6/31

- 4 -

© Department of ETE, CEET, PU.

To be able to keep track of the vectors you create, you can give them names. For example, a row vector v

can be created:

>> v = [0:2:8]

v =

0 2 4 6 8

>> v

v =

0 2 4 6 8

>> v;>> v'

ans =

02468

 Note that in the previous example, if you end the line with a semi-colon, the result is not displayed. This will

come in handy later when you want to use Matlab to work with very large systems of equations.

Matlab will allow you to look at specific parts of the vector. If you want to only look at the first three entries

in a vector you can use the same notation you used to create the vector:

>> v(1:3)

ans =

0 2 4

1.1.2.  Basic operations on vectors

Once you master the notation you are free to perform other operations:

>> v(1:3)-v(2:4)

ans =

-2 -2 -2For the most part Matlab follows the standard notation used in linear algebra. We will see later that there are

some extensions to make some operations easier. For now, though, both addition subtraction are defined in

the standard way. For example, to define a new vector with the numbers from 0 to -4 in steps of -1 we do the

following:

>> u = [0:-1:4]Empty matrix

>> u = [0:-1:-4]

Page 7: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 7/31

- 5 -

© Department of ETE, CEET, PU.

u =

0 -1 -2 -3 -4We can now add u and v together in the standard way:

>> u+v

ans =

0 1 2 3 4

Additionally, scalar multiplication is defined in the standard way. Also note that scalar division is defined in

a way that is consistent with scalar multiplication:

>> -2*u

ans =

0 2 4 6 8

>> v/3

ans =

0 0.6667 1.3333 2.0000 2.6667

With these definitions linear combinations of vectors can be easily defined and the basic operations

combined:

>> -2*u+v/3

ans =

0 2.6667 5.3333 8.0000 10.6667

You will need to be careful. These operations can only be carried out when the dimensions of the vectors

allow it. You will likely get used to seeing the following error message which follows from adding two

vectors whose dimensions are different:

>> u+v'??? Error using ==> plusMatrix dimensions must agree.

Page 8: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 8/31

- 6 -

© Department of ETE, CEET, PU.

1.2.  Simple arithmetic with Matlab

The basic arithmetic operators are +, -, * (for multiplication), / (for divide) & ^ for 

 powers. Where necessary brackets should be used to make the order in which things

are evaluated completely clear.

Enter the following commands to learn the basic way that formulas can be evaluated in Matlab (press enter 

after you have typed in the command. Record the answer beside the command.

>> 3 + 5 -7

The result of this calculation is stored in the temporary variable called ans.It is changed when you do

another calculation. If you want to save the answer from a calculation you can give it a name e.g.

>> t = 3 + 5 - 7

This line creates a variable t to save the answer in. If you want to find out what t is use

>> t 

Equally you can use t in a formula

>> 2*t + 2

In the following calculation does Matlab do the * or the ^ first

>> 3^2*4

Compare the following commands and make sure that you understand what is happening and why you get

the answer 

>> 3 – 4/4 –2

>> (3-4)/(4-2)

>> (3-4)/4 –2

1.2.1.  Extended arithmetic (IEEE)

You need to understand the following section to interpret the output from some calculations particularly

when we make accidental errors.

What does Matlab produce if you ask it to find:

>> 1/0

>> -1/0

>> 0/0

>> 1/Inf 

Page 9: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 9/31

- 7 -

© Department of ETE, CEET, PU.

The symbols Inf (meaning infinity) and NaN (not a well defined number) are part of a special standard for 

computer arithmetic. This is the IEEE international standard for extended arithmetic. Typically you get Inf 

from 1/0 and NaN from 0/0 type calculations. While Inf and NaN are usually signs of bad problem setup

Matlab will try to manipulate these results consistently.

For example extended arithmetic will ensure that 1/( 1/x) always equals x. Test this out by asking Matlab to

calculate

>> 1/(1/0)

Matlab can also handle complex numbers – they are entered as 1 + i or -1+3*I etc .The symbol i is

 best kept as a reserved symbol (Matlab also interprets j as a complex number 

To fit in with usage in electrical engineering)

1.3.  Predefined Variables And Functions

There are several predefined variables which can be used at any time, in the same manner as userdefinedvariables:

i sqrt(-1)

  j sqrt(-1)

  pi 3.1416...

For example,

>>y= 2*(1+4*j)

>>y=

2.0000 + 8.0000i

There are also a number of predefined functions that can be used when defining a variable. Some common

functions that are used in this text are:

abs magnitude of a number (absolute value for real numbers)

angle angle of a complex number, in radians

cos cosine function, assumes argument is in radians

sin sine function, assumes argument is in radians

exp exponential function

‘‘tan, sec, cosec and cotan’’ are also there.

For example, with y defined as above,

>>c = abs(y)>>c =8.2462

>>c = angle(y)>>c =1.3258 

Page 10: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 10/31

- 8 -

© Department of ETE, CEET, PU.

With a=3 as defined previously,

>>c = cos(a)>>c =-0.9900

>>c = exp(a)>>c =

20.0855 

 Note that exp can be used on complex numbers. For example, with y = 2+8i as defined above,

>>c = exp(y)>>c =

-1.0751 + 7.3104i

>>Sin(pi/4)

>>Cos(pi/4  )

1.4.  Logarithm functions

log is log to base e, while log10 and log2 are logs to bases 10 or 2

1.5. Hyperbolic functions

cosh, sinh, and tanh

Page 11: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 11/31

- 9 -

© Department of ETE, CEET, PU.

2. Matrices

Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a column of row

vectors (note that the spaces are required!):>> A = [ 1 2 3; 3 4 5; 6 7 8]

A =

1 2 33 4 56 7 8

You can also treat it like a row of column vectors:>> B = [ [1 2 3]' [2 4 7]' [3 5 8]']

B =

1 2 32 4 53 7 8

(Again, it is important to include the spaces.)>> v = [0:2:8]

v =

0 2 4 6 8

>> A*v(1:3)??? Error using ==> *Inner matrix dimensions must agree.

>> A*v(1:3)'

ans =

162846

Get used to seeing that particular error message! Once you start throwing matrices and vectors around, it is

easy to forget the sizes of the things you have created.

2.1. Basic matrix operations

The symbols for matrix addition, subtraction, multiplication and powers are +, -, * and ^ If a is a squarematrix then a^2 means a*a - the matrix product of a with itself. Define the following matrices and see what

happens with the matrix commands (see the last page to revise the definition of matrix multiplication).

Write Matlab commands that will create the following matrices

Page 12: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 12/31

- 10 -

© Department of ETE, CEET, PU.

 Now try to find (if the answer exists check that it is correct by hand)

>> b + c

>> b – 2*c

>> a + b 

Matlab also does matrix multiplication (provided that the matrices can be multiplied consistently).

First calculate b*a by hand and then use Matlab to check your answer 

>> b*b*b 

>> b^3

>> a*b

More complicated algebraic expressions like b + c – (b^2)*c can also be found.

2.1.1. Solving Of Linear Equations

We write this in the symbolic form

A.x = b

Step 1 Define the matrix A - fill in the definition

>> A = [ 0 1 2; 1 2 1; 3 5 2]

Step 2 Define column vector b

>> b = [ 1; 3; 7]

Step 3 Solve for x using the backslash command

>> x = A\b

(notice that we do not have to define a symbolic vector containing the x, y, z symbols. The variable x is the

column vector containing the numerical solutions to the equations)

Page 13: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 13/31

- 11 -

© Department of ETE, CEET, PU.

Matlab returns the value

x = -2.00003.0000-1.0000 

Step 4 Check that this is really a solution by calculating the difference between the

two sides of the equation – this is A*x - b

>> A*x - b

Matlab returns the value

ans = 000Be careful to get the order correct and the direction of the slash, b\A will be quite different.

2.1.2. Practice the use of the backslash command

Use the \ command to solve the following two equations and check that the Matlab solution is correct.

X =

A*x =

2.1.2.1. The dot symbol

The dot symbol is special to Matlab – it is not a standard mathematical notation and should not be confused

with the dot product of two vectors.

It changes the meaning of ^ in a very important way.

If a is a square matrix then a^2 means a*a - the matrix product of a with itself.

But a.^2 means that we get a new matrix by squaring each element in it separately.

Even if a is not square (so that a*a is not defined) we can still define a.^2

>> a.^2

Page 14: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 14/31

- 12 -

© Department of ETE, CEET, PU.

>> b.^2 

>> b^2

See the answers and try to understand.

Functions are applied element by element. For example,

t = 0:10;

x = cos(2*t);

Creates a vector x with elements equal to cos(2t) for t = 0, 1, 2, ..., 10.Operations that need to be

 performed element-by-element can be accomplished by preceding the operation by a ".". For example, to

obtain a vector x that contains the elements of x(t) = tcos(t) at specific points in time, you cannot simply

multiply the vector t with the vector cos(t). Instead you multiply their elements together:

t = 0:10;

x = t.*cos(t); 

2.2. Creating Longer Vectors And Plotting Graphs

One very useful feature of Matlab is its ability to plot graphs of functions quickly. For example suppose that

we want to plot the graphs of  y= x2 between 0 and 5.

Step 1: Create a vector of 100 evenly spaced points between 0 & 5

>> x = linspace( 0, 5, 100);

The semicolon (;) is used to stop Matlab printing all 100 numbers out.

Step 2: Compute the y values for the curve y= x2

>> y = x.^2;

[the dot here is very important - it squares the elements of x one at a time]

Step 3 Plot just the graph of  y= x2

>> plot( x, y ); grid; shg

Here I put three commands on the one line – grid puts dotted lines on the graph to make it easier to

interpret. The shg command means ‘show graph’.

If the graph does not appear automatically go to the Window menu and select figure 1

Page 15: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 15/31

- 13 -

© Department of ETE, CEET, PU.

2.2.1. Adding titles and labels to a graph 

You can add labels to the x and y axes and also put a title on the graph as shown below. Often the label on

the x axis is used as a description of the graph. You do not have to add labels or titles to graphs but if you

are generating a graph to paste in a Word document then labels and/or title are very useful.

The following graph was generated by the commands

>> plot(x, y); grid

>> xlabel(‘ x values’ )

>> ylabel(‘ y values’ )

>> title(‘Plot of y = x^2 ' )

2.2.2. Putting several graphs of the one plot

Suppose that I want to compare the graphs of  y= , y= x2 and y= x3 over the interval from -2 to +2.

We need to set up the x array (fill this in yourself)

 Next we need to calculate the coordinates on these three graphs

>> y1 = x;

>> y2 = x.^2;

>> y3 =

Page 16: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 16/31

- 14 -

© Department of ETE, CEET, PU.

An extended version of plot can take more pairs of x, y arrays. 

Each x, y pair is added to the graph

>> plot( x, y1, x, y2, x, y3 ); grid; shg [try this yourself]

Add in the grid and the shg command as well

Matlab uses a default colour scheme that usually plots them using colours in the order blue first, then greenand then red.

You can control the colour scheme yourself – e.g. the following command makes the graphs blue, black and

green

>> plot(x, y1, ‘b’, x, y2, ‘k’, x, y3, ‘g’); grid; shg [try this yourself]

You can change the colours or the style of the three plots yourself by adding a third ‘style parameter to any

(or all) of the x, y pairs.

This is typical of Matlab – to make plots you have to give the x & y data and then there are optional things

that you do the plot.

You can change the colour and style of the different lines in the graph

Style refers to the way that the curve appears – a solid line, a dotted line, a line made up of circles etc and/or 

to the colour of the curve.

The complete list of style options is

Examples

>> plot( x, y, ’b’) plots the graph in blue as a solid line (default)

Page 17: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 17/31

Page 18: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 18/31

- 16 -

© Department of ETE, CEET, PU.

In most other languages (e.g. Pascal, C, Java) if you wanted to do this calculation you would need to set up a

loop to process the three entries individually. In Matlab the loop is done for us so that it is very easy to do

many calculations Matlab does not do these things by magic – behind the scenes is a sophisticated ‘engine’

that collects your commands and interprets them.

In Matlab many functions (e.g. sin, cos, log, exp, sqrt ) all accept vector input and give vector output.

For Example

>>t=0:0.25:7;

>>y = sin(t);

>>plot(t,y)

Exercise#2

Use this and your knowledge of graphics command to write down the commands that will plot thegraph of y = cos(x) between x = 0 and x = 10 using 300 sample points.

The problem that you will encounter most often when plotting functions is that MATLAB will scale the axes

in a way that is different than you want them to appear. You can easily override the autoscaling of the axes

 by using the axis command after the plotting command:

axis([xmin xmax ymin ymax]);

where xmin, xmax, ymin, and ymax are numbers corresponding to the limits you desire for the axes.

To return to the automatic scaling, simply type axis.

For discrete-time signals, use the command stem which plots each point with a small open circle and astraight line. To plot y[k] versus k, type stem(k,y). To obtain filled circles, as the plots appear in the

textbook, use the command stem(k,y,'filled').

To plot more than one graph on the screen, use the command subplot(mnp) which partitions the screen into

an mxn grid where p determines the position of the particular graph counting the upper left corner as p=1.

For example,

subplot(211),semilogx(w,magdb);

subplot(212),semilogx(w,phase);

Plots the bode plot with the log-magnitude plot on top and the phase plot below. Titles and labels can beinserted immediately after the appropriate semilogx command or plot command. To return to a full screen

 plot, type subplot(111).

Page 19: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 19/31

- 17 -

© Department of ETE, CEET, PU.

3. M-files

M-files are macros of MATLAB commands that are stored as ordinary text files with the extension "m",

that is filename.m. An M-file can be either a function with input and output variables or a list of commands.

The following describes the use of M-files on a PC version of MATLAB. MATLAB requires that the M-file

must be stored either in the working directory or in a directory that is specified in the MATLAB path list.

For example, consider using MATLAB on a PC with a user-defined M-file stored in a directory called"\MATLAB\MFILES". Then to access that M-file, either change the working directory by typing

cd\matlab\mfiles from within the MATLAB command window or by adding the directory to the path.

Permanent addition to the path is accomplished by editing the \MATLAB\matlabrc.m file, while temporary

modification to the path is accomplished by typing path(path,'\matlab\mfiles') from within MATLAB.

As example of an M-file that defines a function, create a file in your working directory named

yplusx.m that contains the following commands:

function z = yplusx(y,x) z = y + x; 

The following commands typed from within MATLAB demonstrate how this M-file is used:

x = 2; y = 3; z = yplusx(y,x) 

MATLAB M-files are most efficient when written in a way that utilizes matrix or vector operations. Loops

and if statements are available, but should be used sparingly since they are computationally inefficient. An

example of the use of the command for is

for k=1:10, x(k) = cos(k); 

end 

This creates a 1x10 vector x containing the cosine of the positive integers from 1 to 10. This operation is

 performed more efficiently with the commands

k = 1:10; x = cos(k); 

which utilizes a function of a vector instead of a for loop. An if statement can be used to define

conditional statements. An example is

if(a <= 2), b = 1; elseif(a >=4) b = 2; else 

b = 3; end 

The allowable comparisons between expressions are >=, <=, <, >, ==, and ~=. Several of the M-

files written for this textbook employ a user-defined variable which is defined with the command input. For 

Page 20: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 20/31

- 18 -

© Department of ETE, CEET, PU.

example, suppose that you want to run an M-file with different values of a variable T. The following

command line within the M-file defines the value:

T = input('Input the value of T: ') 

Whatever comment is between the quotation marks is displayed to the screen when the M-file is

running, and the user must enter an appropriate value.

Loading and Saving Data 

When using MATLAB, you may wish to leave the program but save the vectors and matrices you have

defined. To save the file to the working directory, type

save filename

where "filename" is a name of your choice. To retrieve the data later, type

load filename

Page 21: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 21/31

- 19 -

© Department of ETE, CEET, PU.

4.SIGNALS AND SYSTEMS

4.1.  Creating and Plotting Variables:Let there is a signal

you could use the following MATLAB commands to create vectors representing the indices and signal

>> n = [-3:3];>> x = 2*n;

 Note that the : is a Matlab shortcut for “all the integers between”, i.e. in this case we obtain {−3,−2,−1, 0, 1,

2, 3}. The ; at the end of each line tells Matlab to be quiet. If you leave off the semicolon, Matlab will echo

to the screen what it is doing, for example

>> n = [-3:3]

n = -3 -2 -1 0 1 2 3

 Now, try plotting this signal using the stem command to plot discrete-time

sequences:

>> stem(n,x)

A window will appear showing the signal for n = [−3,−2, . . . , 2, 3]. If you would like to see the signal in a

larger range, try the following

>> x = [zeros(1,3) n zeros(1,3)];

>> n2 = [-6:6];

>> stem(n2,x)

4.2.  Signal Energy

We can easily calculate the energy of signals in Matlab using a combination of the sum,

abs, and ^ commands, as follows

>> n = [-3:3];>> x = 2*n;>> energy = sum(abs(x).^2)

energy = 112

Page 22: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 22/31

- 20 -

© Department of ETE, CEET, PU.

A few notes are in order here. First, the command .^ tells Matlab to apply the exponentiation operation (the

^) to each element of the vector (or matrix) individually — this is referred to as element-by-element

exponentiation. The command abs works element-by-element as well, e.g.

>> abs([-2 -3 5 -1 9])

ans = 2 3 5 1 9

while, on the other hand, the sum operation returns the total of the elements in a vector, e.g.

>> sum([1:10])

ans = 55 

Consult the Matlab help for the details of the sum command when dealing with matrices.

4.3.  Continuous-time Variables

Creating and Plotting

Matlab does not have support for true continuous-time functions e.g. sin(t). However, we can easily create

such functions in an approximate way by choosing discrete-time functions with a very small step size. For 

example

>> t = 0:0.01:10;>> y = sin(t); 

creates an approximation of a continuous-time function. Note the use of the : operator with three arguments

 — this creates a vector t = {0.00, 0.01, 0.02, . . . , 4.98, 4.99, 5.00}. We will refer to functions of this sort as

“continuous” from now on even though, strictly speaking, they are discrete.

To plot a continuous function, use the plot command, e.g.

>> t = 0:0.01:10;>> y = sin(t);>> plot(t,y)

Try modifying the example above to calculate and plot:

• sin(2t)

• sin(5t−

_/4)• cos(3t + _/2)

(hint: look at the help for cos and pi).

Page 23: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 23/31

- 21 -

© Department of ETE, CEET, PU.

4.4.  Complex Exponentials

Matlab fully supports complex numbers. Both i and j refer to the imaginary unit. In the exercises below, we

will create and plot some complex signals. 

Creating Complex Signals:

Creating complex signals in Matlab follows the same procedure as creating real signals. For example, if wewant to create the complex exponential x1(t) = 2exp(j(t+pi/4))u(t)

>> t = 0:0.01:10;>> x1 = 2*exp(j*(t+pi/4));

 Now, we know that Re{x1(t)} = 2 cos(t+pi/4) and that Im{x1(t)} = 2 sin(t + pi/4), which we can verify by

>> t = 0:0.01:10;>> x1 = 2*exp(j*(t+pi/4));>> xc = real(x1);

>> xs = imag(x1);>> plot(t,xc,’r’,t,2*cos(t+pi/4),’d’);

The last command plots Re{x1(t)} as a solid red line (specified by ’r’), and 2 cos(t+pi/4) as a series of 

diamond characters ( specified by ’d’). As we expect, the two curves are identical and thus totally overlap

each other. Try comparing Im{x1(t)} and 2 sin(t + pi/4) yourself. Also have a look at help plot to see what

other line colours, styles, and symbols are available.

4.4.1.  Plotting Complex SignalsAs you might expect, plotting complex signals is slightly more complicated than plotting real-valued signals,

since we require 3 axes to represent the real, imaginary, and time components of the signal. Fortunately,

Matlab has built-in support for 3-D plotting using the plot3 command. For example, 

>> t = 0:0.01:10;>> x1 = 2*exp(j*(t+pi/4));>> plot3(t,real(x1),imag(x1));

 produces a 3-D plot of the spiralling function x1(t). Try using the zoom and rotate tools in the toolbar of the

 plot window in order to look at the plot from different angles. Now try plotting the exponentially-decaying

complex function x2(t) = 2exp(−0.25t)exp(j(t+pi/4))u(t) as shown below

>> t = 0:0.01:10;>> x2 = 2*exp(-0.25*t).*exp(j*(t+pi/4));>> plot3(t,real(x2),imag(x2));

Again, the .* operation represents element-by-element multiplication. If you leave out the ., Matlab will try

do do a matrix multiplication and will give you an error due to a dimension mismatch.

Try creating and plotting the following complex signals.

Page 24: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 24/31

- 22 -

© Department of ETE, CEET, PU.

• x1(t) = jexp (j10t)

• x2(t) = exp ((−1+j)t)

• x3[n] = exp (j7_n)

• x4[n] = 3exp (j3_(n+1/2)/5)

• x5[n] = 3exp (j3/5(n+1/2))

(remember to choose a suitable values for t and n in order to see several periods of the

function).

4.5.  Ploting of signals

IN MATLAB

N=30;n=0:N-1;x=0.9.^n;h=0.8.^n;subplot(121), stem(n,x), xlabel('n'),title('Signal x(n)')subplot(122), stem(n,h), xlabel('n'),title('Signal h(n)')

Page 25: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 25/31

- 23 -

© Department of ETE, CEET, PU.

SIGNALS:

x1(n) = sin(2πn/16), n = 0, 1, …, 63

x2(n) = sin(2π1.3n/16), n = 0, 1, …, 63x3(n) = sin(2π17n/16), n = 0, 1, …, 63

x4(n) = sin(2πn/32), n = 0, 1, …, 63

x5(n) = sin(2πn/64), n = 0, 1, …, 63

IN MATLAB

>>n=[0:63]';

>>x1=sin(2*pi*n/16);

>>subplot(5,1,1)>>stem(n,x1);>>ylabel('x1')

>>x2=sin(2*pi*1.3*n/16);

>>subplot(5,1,2)>>stem(n,x2);>>ylabel('x2')

>>x3=sin(2*pi*17*n/16);

>>subplot(5,1,3)>>stem(n,x3);>>ylabel('x3')

>>x4=sin(2*pi*n/32);

>>subplot(5,1,4)

>>stem(n,x4);>>ylabel('x4')>>x5=sin(2*pi*n/64);

>>subplot(5,1,5)>>stem(n,x5);

>>xlabel('n'),ylabel('x5')

Page 26: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 26/31

- 24 -

© Department of ETE, CEET, PU.

SIGNALS:

h1(n) = 0.9n

, n = 0, 1, …, 63

h2(n) = 0.8n

, n = 0, 1, …, 63

h3(n) = 0.7n

, n = 0, 1, …, 63

IN MATLAB:

>>n=[0:63]' >>h1=0.9.^n;

>>h2=0.8.^n;

>>h3=0.7.^n;

>>stem(n,h1)>>hold on

>>stem(n,h2)>>stem(n,h3)

>>xlabel('n')

Page 27: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 27/31

- 25 -

© Department of ETE, CEET, PU.

SIGNALS: 

h1(n) = (−0.9)n

, n = 0, 1, …, 63

h2(n) = (−0.8)

n

, n = 0, 1, …, 63h3(n) = (−0.7)

n

, n = 0, 1, …, 63

IN MATLAB:

>>h1=(-0.9).^n;

>>h2=(-0.8).^n;

>>h3=(-0.7).^n;

>>stem(n,h1)>>hold on>>stem(n,h2)>>stem(n,h3) >>xlabel('n')

Page 28: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 28/31

- 26 -

© Department of ETE, CEET, PU.

4.6.  Ploting And Multiplication of Signals

>>y=x1.*h1;

>>stem(n,y)

>>xlabel('n')

Page 29: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 29/31

Page 30: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 30/31

- 28 -

© Department of ETE, CEET, PU.

Example

IN MATLAB

>>N=30;

>>n=0:N-1;>>x=0.9.^n;>>h=0.8.^n; 

>>y=conv(x,h);

>>ny=0:2*N-2;>>stem(ny,y)>> xlabel('n')>>title('Signal y(n)')

Page 31: Copy of MATLAB (Lab Manuals)

8/8/2019 Copy of MATLAB (Lab Manuals)

http://slidepdf.com/reader/full/copy-of-matlab-lab-manuals 31/31

- 29 -

6. Fourier Analysis 

Commands covered:

dftidft

The dft command uses a straightforward method to compute the discrete Fourier transform. Define a vector 

x and compute the DFT using the command

>>X = dft(x)

The first element in X corresponds to the value of X(0).

The command idft uses a straightforward method to compute the inverse discrete Fourier transform. Define

a vector X and compute the IDFT using the command

>>x = idft(X)

Use ‘help’ to se functionality of commands ‘dft’ and ‘idft’.