Sie sind auf Seite 1von 139

1

Table of Contents
Lab 1: Getting Started With Matlab .............................................................................................. 2
Lab 2: Introduction to Matrix ......................................................................................................... 9
Lab 3: Programing in Matlab ....................................................................................................... 18
Lab 4: Introduction to Graphics ................................................................................................... 35
Lab 5: Linear Algebra using MATLAB ....................................................................................... 47
Lab 6: Introduction to Signals ...................................................................................................... 64
Lab 7: Signals Transformation ..................................................................................................... 77
Lab 8: Sampling, periodicity, Harmonics and Sound Manipulation ...................................... 84
Lab 9: Convolution and LTI Systems .......................................................................................... 95
Lab 10: Laplace-Transform ....................................................................................................... 104
Lab 11: Z-transform and Inverse Z-transform Analysis...................................................... 108
Lab 12: Fourier series and the Gibbs Phenomenon ............................................................... 114
Lab 13: Discrete-Time Signals in the Frequency Domain .................................................... 119
Lab 14: Discrete Fourier Transform ........................................................................................ 129
Lab 15: Introduction to SIMULINK ........................................................................................ 136


2

Lab 1: Getting Started With Matlab
The purpose of this Lab is to present basics of MATLAB. We do not assume any prior knowledge of
this package. This Lab is intended for users running a professional version of MATLAB 7, Release 14
under Windows XP or Latest. Topics discussed in this Lab include the Command Window, numbers
and arithmetic operations, saving and reloading a work, using help, MATLAB demos, interrupting a
running program, long command lines, and MATLAB resources on the Internet.
Main MATLAB Interface
Some MATLAB Development Windows
Command Window: where you enter commands
Command History: running history of commands which is preserved across MATLAB sessions
Current directory: Default is $matlabroot/work
Workspace: GUI for viewing, loading and saving MATLAB variables
Array Editor: GUI for viewing and/or modifying contents of MATLAB variables (double-click the
arrays name in the Workspace)
Editor/Debugger: text editor, debugger; editor works with file types in addition to .m (MATLAB
m-files)
MATLAB Editor window

3


The MATLAB Editor Window is the window where MATLAB programs are written and edited.
MATLAB offers users to either write commands in the Command Window where they are executed
one by one, or to write the whole program in the Editor Window where the whole program can be
written, saved as *.m file and can be executed at once anytime.

MATLAB Help Window

MATLAB offers a very powerful Help Window where the user can search for anything related to the
MATLAB version being used.
1.1 The Command Window
You can start MATLAB by double clicking on the MATLAB icon that should be on the desktop of
your computer. This brings up the window called the Command Window. This window allows a user
to enter simple commands. To clear the Command Window type clc and next press the Enter or
Return key. To perform a simple computations type a command and next press the Enter or Return
key. For instance,
s = 1 + 2
s =
3
fun = sin(pi/4)

fun =
0.7071
In the second example the trigonometric function sine and the constant are used. In MATLAB they
are named sin and pi, respectively.
Note that the results of these computations are saved in variables whose names are chosen by the
user. If they will be needed during your current MATLAB session, then you can obtain their values
typing their names and pressing the Enter or Return key. For instance,
s

4

s =
3
Variable name begins with a letter, followed by letters, numbers or underscores. MATLAB
recognizes only the first 31 characters of a variable name.

To change a format of numbers displayed in the Command Window you can use one of the several
formats that are available in MATLAB. The default format is called short (four digits after the
decimal point.) In order to display more digits click on File, select Preferences, and next select a
format you wish to use. They are listed below the Numeric Format. Next click on Apply and OK
and close the current window. You can also select a new format from within the Command Window.
For instance, the following command
format long
changes a current format to the format long. To display more digits of the variable fun type
fun
fun =
0.70710678118655
To change a current format to the default one type
format short
fun
fun =
0.7071
To close MATLAB type exit in the Command Window and next press Enter or Return key. A
second way to close your current MATLAB session is to select File in the MATLAB's toolbar and
next click on Exit MATLAB option. All unsaved information residing in the MATLAB Workspace
will be lost.
1.1.1 Numbers and Arithmetic operations
There are three kinds of numbers used in MATLAB:
- integers
- real numbers
- complex numbers
Integers are entered without the decimal point
xi = 10
xi =
10
However, the following number
xr = 10.01
xr =
10.0100
is saved as the real number. It is not our intention to discuss here machine representation of numbers.
This topic is usually included in the numerical analysis courses. Variables realmin and realmax
denote the smallest and the largest positive real numbers in MATLAB. For instance,
realmin
ans =
2.2251e-308

5

Complex numbers in MATLAB are represented in rectangular form. The imaginary unit 1is
denoted either by i or j
i
ans =
0 + 1.0000i
In addition to classes of numbers mentioned above, MATLAB has three variables representing the
non numbers:
- -Inf
- Inf
- NaN
The Inf and Inf are the IEEE representations for the negative and positive infinity, respectively.
Infinity is generated by overflow or by the operation of dividing by zero. The NaN stands for the not-
a-number and is obtained as a result of the mathematically undefined operations such as
0.0/0.0 or .
List of basic arithmetic operations in MATLAB include six operations

MATLAB has two division operators / - the right division and \ - the left division. They do not
produce the same results
rd = 47/3
rd =
15.6667
ld = 47\3
ld =
0.0638
1.1.2 Saving and Reloading your Work
All variables used in the current MATLAB session are saved in the Workspace. You can view the
content of the Workspace by clicking on File in the toolbar and next selecting Show Workspace from
the pull-down menu. You can also check contents of the Workspace typing whos in the Command
Window. For instance,
whos
Name Size Bytes Class
ans 1x1 16 double array (complex)
fun 1x1 8 double array
ld 1x1 8 double array
rd 1x1 8 double array
s 1x1 8 double array
xi 1x1 8 double array

6

xr 1x1 8 double array
Grand total is 7 elements using 64 bytes
shows all variables used in current session. You can also use command who to generate a list of
variables used in current session
who
Your variables are:
ans ld s xr
fun rd xi
To save your current workspace select Save Workspace as from the File menu. Chose a name for
your file, e.g. filename.mat and next click on Save. Remember that the file you just created must be
located in MATLAB's search path. Another way of saving your workspace is to type save filename in
the Command Window. The following command save filename s saves only the variable s.

Another way to save your workspace is to type the command diary filename in the Command
Window. All commands and variables created from now will be saved in your file. The following
command: diary off will close the file and save it as the text file. You can open this file in a text
editor, by double clicking on the name of your file, and modify its contents if you wish to do so.

To load contents of the file named filename into MATLAB's workspace type load filename in
the Command Window.

More advanced computations often require execution of several lines of computer code. Rather than
typing those commands in the Command Window you should create a file. Each time you will need
to repeat computations just invoke your file. Another advantage of using files is the ease to modify its
contents. To learn more about files, see [1], pp. 67- 75 and also Section 2.2 of Lab 2.
1.2 Help
One of the nice features of MATLAB is its help system. To learn more about a function you are
to use, say rref, type in the Command Window
help svd
SVD Singular value decomposition.
[U,S,V] = SVD(X) produces a diagonal matrix S, of the samedimension as X
and with nonnegative diagonal elements indecreasing order, and unitary
matrices U and V so that
X = U*S*V'.
S = SVD(X) returns a vector containing the singular values.
[U,S,V] = SVD(X,0) produces the "economy size"decomposition. If X is m-by-n
with m > n, then only thefirst n columns of U are computed and S is n-by-n.

See also SVDS, GSVD.

Overloaded methods
help sym/svd.m

7

If you do not remember the exact name of a function you want to learn more about use command
lookfor followed by the incomplete name of a function in the Command Window. In the following
example we use a "word" sv
lookfor sv
ISVMS True for the VMS version of MATLAB.
HSV2RGB Convert hue-saturation-value colors to red-green-blue.
RGB2HSV Convert red-green-blue colors to hue-saturation-value.
GSVD Generalized Singular Value Decomposition.
SVD Singular value decomposition.
SVDS Find a few singular values and vectors.
HSV Hue-saturation-value color map.
JET Variant of HSV.
CSVREAD Read a comma separated value file.
CSVWRITE Write a comma separated value file.
ISVARNAME Check for a valid variable name.
RANDSVD Random matrix with pre-assigned singular values.
Trusvibs.m: % Example: trusvibs
SVD Symbolic singular value decomposition.
RANDSVD Random matrix with pre-assigned singular values.
The helpwin command, invoked without arguments, opens a new window on the screen. To find an
information you need double click on the name of the subdirectory and next double click on a
function to see the help text for that function. You can go directly to the help text of your function
invoking helpwin command followed by an argument. For instance, executing the following
command.
helpwin zeros
ZEROS Zeros array.
ZEROS(N) is an N-by-N matrix of zeros.
ZEROS(M,N) or ZEROS([M,N]) is an M-by-N matrix of zeros.
ZEROS(M,N,P,...) or ZEROS([M N P ...]) is an M-by-N-by-P-by-...
array of zeros.
ZEROS(SIZE(A)) is the same size as A and all zeros.
See also ONES.
generates an information about MATLAB's function zeros.

MATLAB also provides the browser-based help. In order to access these help files click on Help and
next select Help Desk (HTML). This will launch your Web browser. To access information you need
click on a highlighted link or type a name of a function in the text box. In order for the Help Desk to
work properly on your computer the appropriate help files, in the HTML or PDF format, must be
installed on your computer. You should be aware that these files require a significant amount of the
disk space.
1.3 Demos
To learn more about MATLAB capabilities you can execute the demo command in the Command
Window or click on Help and next select Examples and Demos from the pull-down menu. Some of
the MATLAB demos use both the Command and the Figure windows.

8

To learn about matrices in MATLAB open the demo window using one of the methods described
above. In the left pane select Matrices and in the right pane select Basic matrix operations then
click on Run Basic matrix . Click on the Start >>button to begin the show.

If you are familiar with functions of a complex variable I recommend another demo. Select
Visualization and next 3-D Plots of complex functions. You can generate graphs of simple power
functions by selecting an appropriate button in the current window.
1.3.1 Interrupting a running program
To interrupt a running program press simultaneously the Ctrl-c keys. Sometimes you have to repeat
pressing these keys a couple of times to halt execution of your program. This is not a recommended
way to exit a program, however, in certain circumstances it is a necessity. For instance, a poorly
written computer code can put MATLAB in the infinite loop and this would be the only option you
will have left.
1.3.2 Long Command Lines
To enter a statement that is too long to be typed in one line, use three periods, , followed by Enter
or Return. For instance,
x = sin(1) - sin(2) + sin(3) - sin(4) + sin(5) -...
sin(6) + sin(7) - sin(8) + sin(9) - sin(10)
x =
0.7744
You can suppress output to the screen by adding a semicolon after the statement
u = 2 + 3;
1.3.3 Matlab Resources on internet
If your computer has an access to the Internet you can learn more about MATLAB and also download
user supplied files posted in the public domain. We provide below some pointers to information
related to MATLAB.
- The MathWorks Web site: http://www.mathworks.com/Here you can find information about new
products, MATLAB related books, user supplied files and much more.
- http://dir.yahoo.com/science/mathematics/software/matlab/
- http://www.cse.uiuc.edu/cse301/matlab.html
- The Mastering Matlab Web site: http://www.eece.maine.edu/mm
Recommended link for those who are familiar with the book Mastering Matlab 5.
A Comprehensive Tutorial and Reference, by D. Hanselman and B. Littlefield (see [2].)
1.3.4 References
[1] Getting Started with MATLAB, Version 5, The MathWorks, Inc., 1996.
[2] D. Hanselman and B. Littlefield, Mastering MATLAB 5. A Comprehensive Tutorial and
Reference, Prentice Hall, Upper Saddle River, NJ, 1998.
[3] K. Sigmon, MATLAB Primer, Fifth edition, CRC Press, Boca Raton, 1998.
[4] Using MATLAB, Version 5, The MathWorks, Inc., 1996.
[5] Matlab tutorials Edward Neuman




9

Lab 2: Introduction to Matrix
2.1 Introduction
Matrices are the basic elements of the MATLAB environment. A matrix is a two-dimensional
array consisting of m rows and n columns. Special cases are column vectors (n = 1) and row
vectors (m = 1).
In this section we will illustrate how to apply different operations on matrices. The following
topics are discussed: vectors and matrices in MATLAB, the inverse of a matrix, determinants,
and matrix manipulation.
MATLAB supports two types of operations, known as matrix operations and array
operations. Matrix operations will be discussed first.
2.2 Matrix generation
Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrix
generation and manipulation. Matrices can be generated in several ways.
2.2.1 Entering a vector
A vector is a special case of a matrix. The purpose of this section is to show how to create
vectors and matrices in MATLAB. As discussed earlier, an array of dimension 1xn is called a
row vector, whereas an array of dimension m 1 is called a column vector. The elements of
vectors in MATLAB are enclosed by square brackets and are separated by spaces or by
commas. For example, to enter a row vector, v, type
>> v = [1 4 7 10 13]
v =
1 4 7 10 13
Column vectors are created in a similar way, however, semicolon (;) must separate
thecomponents of a column vector,
>> w = [1;4;7;10;13]
w =
1
4
7
10
13
On the other hand, a row vector is converted to a column vector using the transpose operator.
The transpose operation is denoted by an apostrophe or a single quote (').
>> w = v'
w =
1
4
7
10

10

13
Thus, v(1) is the first element of vector v, v(2) its second element, and so forth. Furthermore,
to access blocks of elements, we use MATLAB's colon notation (:). For example, to access
the first three elements of v, we write,
>> v(1:3)
ans =
1 4 7
Or, all elements from the third through the last elements,
>> v(3,end)
ans =
7 10 13
where end signifies the last element in the vector. If v is a vector, writing
>> v(:)
produces a column vector, whereas writing
>> v(1:end)
produces a row vector.
2.2.2 Entering a matrix
A matrix is an array of numbers. To type a matrix into MATLAB you must
- begin with a square bracket, [
- separate elements in a row with spaces or commas (,)
- use a semicolon (;) to separate rows
- end the matrix with another square bracket, ].
Here is a typical example. To enter a matrix A, such as,
A =
1 2 3
4 5 6
7 8 9

Type,
>> A = [1 2 3; 4 5 6; 7 8 9]
MATLAB then displays the 3 x3 matrix as follows,
A =
1 2 3
4 5 6

11

7 8 9
Note that the use of semicolons (;) here is different from their use mentioned earlier
tosuppress output or to write multiple commands in a single line.Once we have entered the
matrix, it is automatically stored and remembered in theWorkspace. We can refer to it simply
as matrix A. We can then view a particular element ina matrix by specifying its location. We
write,
>> A(2,1)
ans =
4
A(2,1) is an element located in the second row and first column. Its value is 4.
2.2.3 Matrix indexing
We select elements in a matrix just as we did for vectors, but now we need two indices.The
element of row i and column j of the matrix A is denoted by A(i,j). Thus, A(i,j)in MATLAB
refers to the element Aij of matrix A. The first index is the row number andthe second index
is the column number. For example, A(1,3) is an element of first row andthird column.
Here,A(1,3)=3.
Correcting any entry is easy through indexing. Here we substitute A(3,3)=9 by
A(3,3)=0. The result is
>> A(3,3) = 0
A =
1 2 3
4 5 6
7 8 0
Single elements of a matrix are accessed as A(i,j), where i 1 and j 1. Zero or
negativesubscripts are not supported in MATLAB.
2.2.4 Colon operator
The colon operator will prove very useful and understanding how it works is the key to
efficient and convenient usage of MATLAB. It occurs in several different forms.
Often we must deal with matrices or vectors that are too large to enter one element at a time.
For example, suppose we want to enter a vector x consisting of points(0; 0:1; 0:2; 0:3; ;
5). We can use the command
>> x = 0:0.1:5;
The row vector has 51 elements.

12

2.2.5 Linear spacing
On the other hand, there is a command to generate linearly spaced vectors: linspace. Itis
similar to the colon operator (:), but gives direct control over the number of points.
Forexample,
y = linspace(a,b)
generates a row vector y of 100 points linearly spaced between and including a and b.
y = linspace(a,b,n)
generates a row vector y of n points linearly spaced between and including a and b. This
isuseful when we want to divide an interval into a number of subintervals of the same
length.For example,
>> theta = linspace(0,2*pi,101)
divides the interval [0; 2] into 100 equal subintervals, then creating a vector of 101
elements.
2.2.6 Colon operator in a matrix
The colon operator can also be used to pick out a certain row or column. For example,
thestatement A(m: n,k:l ) specifies rows m to n and column k to l. Subscript expressions
referto portions of a matrix. For example,
>> A(2,:)
ans =
4 5 6
is the second row elements of A.The colon operator can also be used to extract a sub-matrix
from a matrix A.
>> A(:,2:3)
ans =
2 3
5 6
8 0
A(:,2:3) is a sub-matrix with the last two columns of A.A row or a column of a matrix can be
deleted by setting it to a null vector, [ ].
>> A(:,2)=[]
ans =
1 3

13

4 6
7 0
2.2.7 Creating a sub-matrix
To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the matrix A,do
the following
>> B = A([2 3],[1 2])
B =
4 5
7 8
To interchange rows 1 and 2 of A, use the vector of row indices together with the
colonoperator.
>> C = A([2 1 3],:)
C =
4 5 6
1 2 3
7 8 0
It is important to note that the colon operator (:) stands for all columns or all rows. Tocreate
a vector version of matrix A, do the following
>> A(:)
ans =
1
2
3
4
5
6
7
8
0
The submatrix comprising the intersection of rows p to q and columns r to s is denoted
byA(p:q,r:s).As a special case, a colon (:) as the row or column specifier covers all entries in
that row orcolumn; thus
- A(:,j) is the jth column of A, while
- A(i,:) is the ith row, and
- A(end,:) picks out the last row of A.

14

The keyword end, used in A(end,:), denotes the last index in the specified dimension. Hereare
some examples.
>> A
A =
1 2 3
4 5 6
7 8 9
>> A(2:3,2:3)
ans =
5 6
8 9
>> A(end:-1:1,end)
ans =
9
6
3
24
>> A([1 3],[2 3])
ans =
2 3
8 9
2.2.8 Deleting row or column
To delete a row or column of a matrix, use the empty vector operator, [ ].
>> A(3,:) = []
A =
1 2 3
4 5 6
Third row of matrix A is now deleted. To restore the third row, we use a technique
forcreating a matrix
>> A = [A(1,:);A(2,:);[7 8 0]]
A =
1 2 3
4 5 6
7 8 0
Matrix A is now restored to its original form.
2.2.9 Dimension
To determine the dimensions of a matrix or vector, use the command size. For example,
>> size(A)
ans =
3 3
means 3 rows and 3 columns.
Or more explicitly with,

15

>> [m,n]=size(A)
2.2.10 Continuation
If it is not possible to type the entire input on the same line, use consecutive periods, calledan
ellipsis , to signal continuation, then continue the input on the next line.
B = [ 4/5 7.23*tan(x) sqrt(6); ...
1/x^2 0 3/(x*log(x)); ...
x-7 sqrt(3) x*sin(x)];
Note that blank spaces around +, - , = signs are optional, but they improve readability.

2.2.11 Transposing a matrix
The transpose operation is denoted by an apostrophe or a single quote ('). It flips a
matrixabout its main diagonal and it turns a row vector into a column vector. Thus,
>> A'
ans =
1 4 7
2 5 8
3 6 0
By using linear algebra notation, the transpose of m n real matrix A is the n m matrixthat
results from interchanging the rows and columns of A. The transpose matrix is denotedAT .
2.2.12 Concatenating matrices
Matrices can be made up of sub-matrices. Here is an example. First, let's recall our
previousmatrix A.
A =
1 2 3
4 5 6
7 8 9
The new matrix B will be,
>> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]]
B =

1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1 0 0
-4 -5 -6 0 1 0
-7 -8 -9 0 0 1
2.3 Matrix generators
MATLAB provides functions that generates elementary matrices. The matrix of zeros,
thematrix of ones, and the identity matrix are returned by the functions zeros, ones, and
eye,respectively.
Table 2.4: Elementary matrices
eye(m,n) Returns an m-by-n matrix with 1 on the main diagonal
eye(n) Returns an n-by-n square identity matrix

16

zeros(m,n) Returns an m-by-n matrix of zeros
ones(m,n) Returns an m-by-n matrix of ones
diag(A) Extracts the diagonal of matrix A
rand(m,n) Returns an m-by-n matrix of random numbers

For a complete list of elementary matrices and matrix manipulations, type help elmator doc
elmat. Here are some examples:
1. >> b=ones(3,1)
b =
1
1
1
Equivalently, we can define b as >> b=[1;1;1]
2. >> eye(3)
ans =
1 0 0
0 1 0
0 0 1
3. >> c=zeros (2, 3)
c =
0 0 0
0 0 0
In addition, it is important to remember that the three elementary operations of addition (+),
subtraction (), and multiplication () apply also to matrices whenever thedimensions are
compatible.
Two other important matrix generation functions are rand and randn, which generatematrices
of (pseudo-)random numbers using the same syntax as eye.In addition, matrices can be
constructed in a block form. With C defined by C = [12; 3 4], we may create a matrix D as
follows
>> D = [C zeros(2); ones(2) eye(2)]
D =
1 2 0 0
3 4 0 0
1 1 1 0
1 1 0 1
2.3.1 Special matrices
MATLAB provides a number of special matrices (see Table 2.5). These matrices have
interesting properties that make them useful for constructing examples and for testing
algorithms.For more information, see MATLAB documentation.
Table 2.5: Special matrices
hilb Hilbert matrix
invhilb Inverse Hilbert matrix
magic Magic square
pascal Pascal matrix
toeplitz Toeplitz matrix
vander vandermonde matrix

17

wilkinson Wilkinson's eigenvalue test matrix
2.3.2 Exercise:INTELLIGENT CRICKET SCORECARD
This is an exercise in matrix manipulation. Suppose that two teams A and B score the
following runs in a game of ten over. Below the number of runs scored and no of wickets
fallen in each over are displayed.
TEAM A
Runs : 8 6 9 0 11 13 6 0 10 3
Wickets : 1 0 2 0 0 0 1 0 0 0

TEAM B
Runs : 9 5 3 0 0 8 13 15 9 0
Wickets : 1 1 0 0 0 0 1 2 0 0

These are to be declared as two 2 x 10 matrices in MATLAB. Write a routine that takes these
matrices as input and generates an intelligent score card for both the teams considering that
team A played first.


TEAM X

Over
No
Runs in
this over
Total
score
Run
average
Wickets in
this over
Total no of
wickets
Run rate
required to
win
1
2
3
4
5
6
7
8
9
10

This table should be returned in the form of a MATRIX for team A and B both. Of course the
last column in the table would hold true only for team playing second.

18

Lab 3: Programing in MATLAB
This Lab is intended for those who want to learn basics of MATLAB programming language. Even
with a limited knowledge of this language a beginning programmer can write his/her own computer
code for solving problems that are complex enough to be solved by other means. Numerous examples
included in this text should help a reader to learn quickly basic programming tools of this language.
Topics discussed include the m-files, inline functions, control flow, relational and logical operators,
strings, cell arrays, rounding numbers to integers and MATLAB graphics.
3.1 The m-files
Files that contain a computer code are called the m-files. There are two kinds of m-files: the script files and the
function files. Script files do not take the input arguments or return the output arguments. The function
files may take input arguments or return output arguments.

To make the m-file click on File next select New and click on M-File from the pull-down menu. You
will be presented with the MATLAB Editor/Debugger screen. Here you will type your code, can
make changes, etc. Once you are done with typing, click on File, in the MATLAB
Editor/Debuggerscreen and select Save As. Chose a name for your file, e.g., firstgraph.m and
click on Save. Make sure that your file is saved in the directory that is in MATLAB's search path.

If you have at least two files with duplicated names, then the one that occurs first in MATLAB's
search path will be executed.

To open the m-file from within the Command Window type edit firstgraph and then press Enter or
Returnkey.

Here is an example of a small script file

% Script file firstgraph.

x = pi/100:pi/100:10*pi;
y = sin(x)./x;
plot(x,y)
grid

Let us analyze contents of this file. First line begins with the percentage sign %. This is a comment.
All comments are ignored by MATLAB. They are added to improve readability of the code. In the
next two lines arrays x and y are created. Note that the semicolon follows both commands. This
suppresses display of the content of both vectors to the screen (see Lab 1 for more details). Array x
holds 1000 evenly spaced numbers in the interval [/100 10/ ] while the array y holds the values of
the sinc function y = sin(x)/x at these points. Note use of the dot operator . before the right division
operator /. This tells MATLAB to perform the component wise division of two arrays sin(x) and x.
Special operators in MATLAB and operations on one- and two dimensional arrays are discussed in
detail in Lab 3, Section 3.2. The command plot creates the graph of the sinc function using the points
generated in two previous lines. For more details about command plot see Section 2.8.1 of this Lab.
Finally, the command grid is executed. This adds a grid to the graph. We invoke this file by typing its
name in the Command Window and next pressing the Enter or Return key
firstgraph


19


3.2 Functions
When you use sin or log or exp in Matlab you are using function m-files. They are different
from script m-files primarily because they have inputs and outputs. To specify which variables in
the m-file are the inputs, and which are the outputs, the first line of the m-file should be in this form:

function output=function_name(input)

For example, an m-file that begins with the line:

function L=vec_length(V)
takes a column vector V as its input, and returns its length L as its output. Here is the complete file
vec_length.m :
function L=vec_length(V)
% returns the length of column vector V
L=sqrt(V' * V); % square root of the dot product of V with itself

You would invoke on the command line this way:
>> W=[1; 2; -3]
>>Length_of_W=vec_length(W)
Several more examples are given. We recommend you make the name of the function given on the
first line match the file name of the m-file, i.e. function vec_length is in file vec_length.m, not in
sillyname.m
We also recommend you put only one function in each m-file (though under some circumstances it is
allowed to group a set of functions together into a single m-file.) If you store all your m-files in the
same directory, any function can call any other function. If you get a message saying that Matlab
cannot find your m-file, on the command line type
>> pwd
to make sure Matlab is looking in the correct folder, and then
>> dir
or
>> ls

20

to make sure that the m-file is really in that folder. You may have accidentally saved it in the wrong
folder.
Here is an example of the function file

function[b, j] = descsort(a)

% Function descsort sorts, in the descending order, a real array a.
% Second output parameter j holds a permutation used to obtain
% array b from the array a.
[b ,j] = sort(-a);
b = -b;
To demonstrate functionality of the function under discussion let
a = [pi 10 35 0.15];
[b, j] = descsort(a)
b =
35.0000 3.1416 0.1500 -10.0000
j =
3 1 4 2
You can execute function descsort without output arguments. In this case an information about a
permutation used will be lost
descsort(a)
ans =
35.0000 3.1416 0.1500 -10.0000
Since no output argument was used in the call to function descorder a sorted array a is assigned
to the default variable ans.
3.2.1 Inline function and feval command
Sometimes it is handy to define a function that will be used during the current MATLAB session
only. MATLAB has a command inline used to define the so-called inline functions in the Command
Window.

Let

f = inline('sqrt(x.^2+y.^2)','x','y')

f =
Inline function:
f(x,y) = sqrt(x.^2+y.^2)

You can evaluate this function in a usual way

f(3,4)
ans =
5

Note that this function also works with arrays. Let

A = [1 2;3 4]

A =
1 2
3 4

and

B = ones(2)

B =
1 1

21

1 1

Then
C = f(A, B)

C =
1.4142 2.2361
3.1623 4.1231
For the later use let us mention briefly a concept of the string in MATLAB. The character string is a
text surrounded by single quotes. For instance,

str = 'programming in MATLAB is fun'

str =
programming in MATLAB is fun
is an example of the string. Strings are discussed in Section 2.5 of this Lab.
In the previous section you have learned how to create the function files. Some functions take as the
input argument a name of another function, which is specified as a string. In order to execute function
specified by string you should use the command feval as shown below

feval('functname', input parameters of function functname)

Consider the problem of computing the least common multiple of two integers. MATLAB has a built-
in function lcm that computes the number in question. Recall that the least common multiple and the
greatest common divisor (gcd) satisfy the following equation

ab = lcm(a, b)gcd(a, b)
MATLAB has its own function, named gcd, for computing the greatest common divisor.
To illustrate the use of the command feval let us take a closer look at the code in the m-file
mylcm

functionc = mylcm(a, b)

% The least common multiple c of two integers a and b.

Iffeval('isint',a) & feval('isint',b)
c = a.*b./gcd(a,b);
else
error('Input arguments must be integral numbers')
end

Command feval is used twice in line two (I do do not count the comment lines and the blank lines). It
checks whether or not both input arguments are integers. The logical and operator&used here is
discussed in Section 2.4. If this condition is satisfied, then the least common multiple is computed
using the formula mentioned earlier, otherwise the error message is generated. Note use of the
command error,which takes as the argument a string. The conditional if - else end used here is
discussed in Section 2.4 of this tutorial. Function that is executed twice in the body of the function
mylcm is named isint

functionk = isint(x);

% Check whether or not x is an integer number.
% If it is, function isint returns 1 otherwise it returns 0.

Ifabs(x - round(x)) < realmin
k = 1;

22

else
k = 0;
end

New functions used here are the absolute value function (abs) and the round function (round). The
former is the classical math function while the latter takes a number and rounds it to the closest
integer. Other functions used to round real numbers to integers are discussed in Section 2.7. Finally,
realmin is the smallest positive real number on your computer

format long

realmin

ans =
2.225073858507201e-308

format short

The Trapezoidal Rule with the correction term is often used to numerical integration of functions that
are differentiable on the interval of integration

where h = b a. This formula is easy to implement in MATLAB


functiony = corrtrap(fname, fpname, a, b)

% Corrected trapezoidal rule y.
% fname - the m-file used to evaluate the integrand,
% fpname - the m-file used to evaluate the first derivative
% of the integrand,
% a,b - endpoinds of the interval of integration.

h = b - a;
y = (h/2).*(feval(fname,a) + feval(fname,b))+ (h.^2)/12.*(...
feval(fpname,a) - feval(fpname,b));


The input parameters aand bcan be arrays of the same dimension. This is possible because the dot
operator proceeds certain arithmetic operations in the command that defines the variable y.

In this example we will integrate the sine function over two intervals whose end points are stored in
the arrays aand b, where

a = [0 0.1];
b = [pi/2 pi/2 + 0.1];

y = corrtrap('sin', 'cos', a, b)

y =
0.9910 1.0850

Since the integrand and its first order derivative are both the built-in functions, there is no need to
define these functions in the m-files.

23

3.3 Control Flow
To control the flow of commands, the makers of MATLAB supplied four devices a programmer
can use while writing his/her computer code

- the for loops
- the whileloops
- the if-else-end constructions
- the switch-case constructions
3.3.1 Repeating with for loop
Syntax of the for loop is shown below

for k = array
commands
end

The commands between the for and end statements are executed for all values stored in the array.

Suppose that one-need values of the sine function at eleven evenly spaced points n/10, for n = 0, 1,
, 10. To generate the numbers in question one can use the for loop
for n=0:10
x(n+1) = sin(pi*n/10);
end


x

x =
Columns 1 through 7
0 0.3090 0.5878 0.8090 0.9511 1.0000
0.9511
Columns 8 through 11
0.8090 0.5878 0.3090 0.0000

The for loops can be nested
H = zeros(5);
for k=1:5
for l=1:5
H(k,l) = 1/(k+l-1);
end
end

H

H =
1.0000 0.5000 0.3333 0.2500 0.2000
0.5000 0.3333 0.2500 0.2000 0.1667
0.3333 0.2500 0.2000 0.1667 0.1429
0.2500 0.2000 0.1667 0.1429 0.1250
0.2000 0.1667 0.1429 0.1250 0.1111
Matrix H created here is called the Hilbert matrix. First command assigns a space in computer's
memory or the matrix to be generated. This is added here to reduce the overhead that is required by
loops in MATLAB.

The for loop should be used only when other methods cannot be applied. Consider the following
problem. Generate a 10-by-10 matrix A = [akl], where akl = sin(k)cos(l). Using nested loops one can
compute entries of the matrix A using the following code.

24

A = zeros(10);
for k=1:10
for l=1:10
A(k,l) = sin(k)*cos(l);
end
end

A loop free version might look like this

k = 1:10;
A = sin(k)'*cos(k);

First command generates a row array k consisting of integers 1, 2, , 10. The command sin(k)'
creates a column vector while cos(k) is the row vector. Components of both vectors are the values of
the two trig functions evaluated at k. Code presented above illustrates a powerful feature of
MATLAB called vectorization. This technique should be used whenever it is possible.
3.3.2 Repeating with while loops
Syntax of the while loop is

while expression
statements
end

This loop is used when the programmer does not know the number of repetitions a priori.
Here is an almost trivial problem that requires a use of this loop. Suppose that the number is divided
by 2. The resulting quotient is divided by 2 again. This process is continued till the current quotient is
less than or equal to 0.01. What is the largest quotient that is greater than 0.01?
To answer this question we write a few lines of code

q = pi;
while q > 0.01
q = q/2;
end

q

q =
0.0061
3.3.3 The if-else-end construction
Syntax of the simplest form of the construction under discussion is

if expression
commands
end
This construction is used if there is one alternative only. Two alternatives require the construction

if expression
commands (evaluated if expression is true)
else
commands (evaluated if expression is false)
end

Construction of this form is used in functions mylcm and isint (see Section 2.3).

If there are several alternatives one should use the following construction

25


if expression1
commands (evaluated if expression 1 is true)
elseif expression 2
commands (evaluated if expression 2 is true)
elseif
.
.
.
else
commands (executed if all previous expressions evaluate to false)
end
Chebyshev polynomialsTn
(x)
, n = 0, 1, of the first kind are of great importance in numerical
analysis. They are defined recursively as follows

Tn(x) = 2xTn 1(x) Tn 2(x), n = 2, 3, , T0(x) = 1, T1(x) = x.

Implementation of this definition is easy
functionT = ChebT(n)

% Coefficients T of the nth Chebyshev polynomial of the first
kind.
% They are stored in the descending order of powers.

t0 = 1;
t1 = [1 0];
if n == 0
T = t0;
elseif n == 1;
T = t1;
else
for k=2:n
T = [2*t1 0] - [0 0 t0];
t0 = t1;
t1 = T;
end
end

Coefficients of the cubic Chebyshev polynomial of the first kind are

coeff = ChebT(3)

coeff =
4 0 -3 0


Thus T3(x) = 4x
3
3x.
3.3.4 The switch-case construction
Syntax of the switch-case construction is

switch expression (scalar or string)
case value1 (executes if expression evaluates to value1)
commands
case value2 (executes if expression evaluates to value2)
commands
.
.

26

.
otherwise
statements
end
Switch compares the input expression to each case value. Once the match is found it executes the
associated commands.
In the following example a random integer number x from the set {1, 2, , 10} is generated. If x = 1
or x= 2, then the message Probability = 20% is displayed to the screen. If x = 3 or 4 or 5, then the
message Probability = 30% is displayed, otherwise the message Probability = 50% is generated. The
script file fswitch utilizes a switch as a tool for handling all cases mentioned above.

% Script file fswitch.

x = ceil(10*rand); % Generate a random integer in {1,
2,...,10}
switch x
case {1,2}
disp('Probability = 20%');
case {3,4,5}
disp('Probability = 30%');
otherwise
disp('Probability = 50%');
end

Note use of the curly braces after the word case. This creates the so-called cell array rather than the
one-dimensional array, which requires use of the square brackets.
Here are new MATLAB functions that are used in file fswitch

rand uniformly distributed random numbers in the interval (0, 1)
ceil round towards plus infinity infinity (see Section 2.5 for more details)
disp display string/array to the screen

Let us test this code ten times

for k = 1:10
fswitch
end

Probability = 50%
Probability = 30%
Probability = 50%
Probability = 50%
Probability = 50%
Probability = 30%
Probability = 20%
Probability = 50%
Probability = 30%
Probability = 50%
3.3.5 Relational and logical operators
Comparisons in MATLAB are performed with the aid of the following operators
Operator Description
< Less than
<= Less than or equal to
> Greater
>= Greater or equal to
== Equal to
~= Not equal to

27

Operator ==compares two variables and returns ones when they are equal and zeros otherwise.

Let

a = [1 1 3 4 1]

a =
1 1 3 4 1

Then
ind = (a == 1)

ind =
1 1 0 0 1

You can extract all entries in the array a that are equal to 1 using

b = a(ind)

b =
1 1 1
This is an example of so-called logical addressing in MATLAB. You can obtain the same result using
function find

ind = find(a == 1)

ind =
1 2 5

Variable indnow holds indices of those entries that satisfy the imposed condition. To extract all ones from the
array a use

b = a(ind)

b =
1 1 1
There are three logical operators available in MATLAB
Logical operator Description
| Or
& And
~ Not
Suppose that one wants to select all entries xthat satisfy the inequalities x>= 1or x < -0.2 where

x = randn(1,7)

x =
-0.4326 -1.6656 0.1253 0.2877 -1.1465 1.1909 1.1892

is the array of normally distributed random numbers. We can solve easily this problem using
operators discussed in this section

ind = (x >= 1) | (x < -0.2)

ind =
1 1 0 0 1 1 1

y = x(ind)
y =

28

-0.4326 -1.6656 -1.1465 1.1909 1.1892

Solve the last problem without using the logical addressing.

In addition to relational and logical operators MATLAB has several logical functions designed for
performing similar tasks. These functions return 1 (true) if a specific condition is satisfied and 0(false)
otherwise. A list of these functions is too long to be included here. The interested reader is referred to
[1], pp. 85-86 and [4], Chapter 10, pp. 26-27. Names of the most of these functions begin with the
prefix is. For instance, the following command

isempty(y)

ans =
0

returns 0 because the array y of the last example is not empty. However, this command

isempty([ ])

ans =
1

returns 1 because the argument of the function used is the empty array [ ].

Here is another example that requires use of the isempty command


functiondp = derp(p)

% Derivative dp of an algebraic polynomial that is
% represented by its coefficients p. They must be stored
% in the descending order of powers.

n = length(p) - 1;
p = p(:)'; % Make sure p is a row array.
dp = p(1:n).*(n:-1:1); % Apply the Power Rule.
k = find(dp ~= 0);
if ~isempty(k)
dp = dp(k(1):end); % Delete leading zeros if any.
else
dp = 0;
end


In this example p(x) = x
3
+ 2x
2
+ 4. Using a convention for representing polynomials in MATLAB as
the array of their coefficients that are stored in the descending order of powers, we obtain
dp = derp([1 2 0 4])

dp =
3 4 0
3.3.6 Rounding to integers. Function ceil, Floor, Round
We have already used two MATLAB functions round and ceil to round real numbers to integers.
They are briefly described in the previous sections of this tutorial. A full list of functions designed for
rounding numbers is provided below
Function Description
Floor Round towards minus infinity
Ceil Round towards plus infinity
Fix Round towards zero

29

Round Round towards nearest integer

To illustrate differences between these functions let us create first a two-dimensional array of random
numbers that are normally distributed (mean = 0, variance = 1) using another MATLAB function
randn

randn('seed', 0) % This sets the seed of the random numbers generator to zero

T = randn(5)
T =
1.1650 1.6961 -1.4462 -0.3600 -0.0449
0.6268 0.0591 -0.7012 -0.1356 -0.7989
0.0751 1.7971 1.2460 -1.3493 -0.7652
0.3516 0.2641 -0.6390 -1.2704 0.8617
-0.6965 0.8717 0.5774 0.9846 -0.0562


A = floor(T)

A =
1 1 -2 -1 -1
0 0 -1 -1 -1
0 1 1 -2 -1
0 0 -1 -2 0
-1 0 0 0 -1


B = ceil(T)

B =
2 2 -1 0 0
1 1 0 0 0
1 2 2 -1 0
1 1 0 -1 1
0 1 1 1 0


C = fix(T)

C =
1 1 -1 0 0
0 0 0 0 0
0 1 1 -1 0
0 0 0 -1 0
0 0 0 0 0



D = round(T)

D =
1 2 -1 0 0
1 0 -1 0 -1
0 2 1 -1 -1
0 0 -1 -1 1
-1 1 1 1 0
In the following m-file functions floor and ceil are used to obtain a certain representation of a
nonnegative real number



30

function [m, r] = rep4(x)

% Given a nonnegative number x, function rep4 computes an integer m
% and a real number r, where 0.25 <= r < 1, such that x = (4^m)*r.

If x == 0
m = 0;
r = 0;
return
end
u = log10(x)/log10(4);
if u < 0
m = floor(u)
else
m = ceil(u);
end
r = x/4^m;

Command returncauses a return to the invoking function or to the keyboard. Function log10 is the
decimal logarithm.

[m, r] = rep4(pi)

m =
1
r =
0.7854

We check this result

format long

(4^m)*r

ans =
3.14159265358979


format short

3.3.7 Reference
[1] D. Hanselman and B. Littlefield, Mastering MATLAB 5. A Comprehensive Tutorial
and Reference, Prentice Hall, Upper Saddle River, NJ, 1998.
[2] P. Marchand, Graphics and GUIs with MATLAB, Second edition, CRC Press, Boca
Raton,1999.
[3] K. Sigmon, MATLAB Primer, Fifth edition, CRC Press, Boca Raton, 1998.
[4] Using MATLAB, Version 5, The MathWorks, Inc., 1996.
[5] Using MATLAB Graphics, Version 5, The MathWorks, Inc., 1996.
3.3.8 Exercise problems
In Problems 1- 4 you cannot use loops foror while.


1. Write MATLAB function sigma = ascsum(x) that takes a one-dimensional array xof real
numbers and computes their sum sigma in the ascending order of magnitudes.Hint: You may
wish to use MATLAB functions sort, sum, and abs.


31

2. In this exercise you are to write MATLAB function d = dsc(c) that takes a one-dimensional
array of numbers cand returns an array d consisting of all numbers in the array cwith all
neighboring duplicated numbers being removed. For instance, if c = [1 2 2 2 3 1], then d = [1
2 3 1].

3. Write MATLAB function p = fact(n) that takes a nonnegative integer n and returns value of
the factorial function n! = 1*2* *n. Add an error message to your code that will be
executed when the input parameter is a negative number

4. Write MATLAB function [in, fr] = infr(x)that takes an array xof real numbers and returns arrays in
and fr holding the integral and fractional parts, respectively, of all numbers in the array x.

5. Given an array band a positive integer mcreate an array d whose entries are those in the array
beach replicated m-times. Write MATLAB function d = repel(b, m) that generates array das
described in this problem.

6. In this exercise you are to write MATLAB function d = rep(b, m) that has more functionality
than the function repel of Problem 5. It takes an array of numbers band the array m of
positive integers and returns an array dwhose each entry is taken from the array b and is
duplicated according to the corresponding value in the array m. For instance, if b = [ 1 2] and
m = [2 3], then d = [1 1 2 2 2].

7. A checkerboard matrix is a square block diagonal matrix, i.e., the only nonzero entries are in
the square blocks along the main diagonal. In this exercise you are to write MATLAB
function A = mysparse(n)that takes an odd number n and returns a checkerboard matrix as
shown below

A = mysparse(3)

A =
1 0 0
0 1 2
0 3 4


A = mysparse(5)
A =
1 0 0 0 0
0 1 2 0 0
0 3 4 0 0
0 0 0 2 3
0 0 0 4 5


A = mysparse(7)


A =
1 0 0 0 0 0 0
0 1 2 0 0 0 0
0 3 4 0 0 0 0
0 0 0 2 3 0 0
0 0 0 4 5 0 0
0 0 0 0 0 3 4
0 0 0 0 0 5 6
First block in the upper-left corner is the 1-by-1 matrix while the remaining blocks are all 2-
by-2.


32

8. The Legendre polynomials Pn(x), n = 0, 1, are defined recursively as follows
nPn(x) = (2n-1)xPn -1 (n-1)Pn-2(x), n = 2, 3, , P0(x) = 1, P1(x) = x.
Write MATLAB function P = LegendP(n) that takes an integer n the degree of Pn
(x)

and returns its coefficient stored in the descending order of powers.

9. In this exercise you are to implement Euclid's Algorithm for computing the greatest common divisor
(gcd) of two integer numbers aand b:
gcd(a, 0) = a, gcd(a, b) = gcd(b, rem(a, b)).
Here rem(a, b) stands for the remainder in dividing a by b. MATLAB has function rem.
Write MATLAB function gcd = mygcd(a,b) that implements Euclid's Algorithm.

10. The Pascale triangle holds coefficients in the series expansion of (1 + x)
n
, where n = 0, 1, 2,
. The top of this triangle, for n = 0, 1, 2, is shown here
1
1 1
1 2 1
Write MATLAB function t = pasctri(n) that generates the Pascal triangle t up to the level n.
Remark. Two-dimensional arrays in MATLAB must have the same number of columns in
each row. In order to aviod error messages you have to add a certain number of zero entries to
the right of last nonzero entry in each row of t but one. This
t = pasctri(2)
t =
1 0 0
1 1 0
1 2 1
is an example of the array t for n = 2.

11. This is a continuation of Problem 10. Write MATLAB function t = binexp(n) that computes
an array t with row k+1 holding coefficients in the series expansion of (1-x)^k, k = 0, 1, ... ,
n, in the ascending order of powers. You may wish to make a call from within your function
to the function pasctri of Problem 10. Your output sholud look like this (case n = 3)
t = binexp(3)
t =
1 0 0 0
1 -1 0 0
1 -2 1 0
1 -3 3 -1

12. MATLAB come with the built-in function mean for computing the unweighted arithmetic
mean of real numbers. Let x = {x1, x2, , xn} be an array of n real numbers. Then

In some problems that arise in mathematical statistics one has to compute the weighted
arithmetic mean of numbers in the array x. The latter, abbreviated here as wam, is defined as
follows

Here w = {w1, w2, , wn} is the array of weights associated with variables x. The weights
are all nonnegative with w1 + w2 + + wn > 0. In this exercise you are to write MATLAB
function y = wam(x, w) that takes the arrays of variables and weights and returns the
weighted arithmetic mean as defined above. Add three error messages to terminate
prematurely execution of this file in the case when:

33

- arrays x and w are of different lengths
- at least one number in the array w is negative
- sum of all weights is equal to zero.

13. Let w = {w1, w2, , wn} be an array of positive numbers. The weighted geometric mean,
abbreviated as wgm, of the nonnegative variables x = {x1, x2, , xn} is defined as follows

Here we assume that the weights w sum up to one. Write MATLAB function y = wgm(x, w)
that takes arrays x and w and returns the weighted geometric mean y of x with weights stored
in the array w. Add three error messages to terminate prematurely execution of this file in the
case when:
- arrays x and w are of different lengths
- at least one variable in the array x is negative
- at least one weight in the array w is less than or equal to zero
Also, normalize the weights w, if necessary, so that they will sum up to one.

14. Write MATLAB function [nonz, mns] = matstat(A) that takes as the input argument a real
matrix A and returns all nonzero entries of A in the column vector nonz. Second output
parameter mns holds values of the unweighted arithmetic means of all columns of A.

15. Solving triangles requires a bit of knowledge of trigonometry. In this exercise you are to write
MATLAB function [a, B, C] = sas(b, A, c) that is intended for solving triangles given two
sides b and c and the angle A between these sides. Your function should determine remaining
two angels and the third side of the triangle to be solved. All angles should be expressed in
the degree measure.

16. Write MATLAB function [A, B, C] = sss(a, b, c) that takes three positive numbers a, b, and
c. If they are sides of a triangle, then your function should return its angles A, B, and C, in the
degree measure, otherwise an error message should be displayed to the screen.

17. In this exercise you are to write MATLAB function dms(x) that takes a nonnegative number
x that represents an angle in the degree measure and converts it to the form x deg. y min. z
sec.. Display a result to the screen using commands disp and sprintf.
Example:
dms(10.2345)
Angle = 10 deg. 14 min. 4 sec.

18. In this exercise you are to model one of the games known as Lottery. Three numbers, with
duplicates allowed, are selected randomly from the set {0,1,2,3,4,5,6,7,8,9} in the game Pick3
and four numbers are selected in the Pick4 game. Write MATLAB function winnumbs =
lotto(n) that takes an integer n as its input parameter and returns an array winnumbs
consisting of n numbers from the set of integers described in this problem. Use MATLAB
function rand together with other functions to generate a set of winning numbers. Add an
error message that is displayed to the screen when the input parameter is out of range.

19. Write MATLAB function t = isodd(A) that takes an array A of nonzero integers and returns
1 if all entries in the array A are odd numbers and 0 otherwise. You may wish to use
MATLAB function rem in your file.

20. Given two one-dimensional arrays a and b, not necessarily of the same length. Write
MATLAB function c = interleave(a, b) which takes arrays a and b and returns an array c
obtained by interleaving entries in the input arrays. For instance, if a = [1, 3, 5, 7] and b = [-2,
4], then c = [1, 2, 3, 4, 5, 7]. Your program should work for empty arrays too.You cannot
use loops for or while.


34








35

Lab 4: Introduction to Graphics
4.1 Plotting
MATLAB contains numerous commands for creating two- and three-dimensional plots.
Themost basic of these commands is plot which can have multiple optional arguments.
Asimple example of this command is to plot a function of time.
t = linspace(0, 8, 401); %Define a vector of times from 0 to 8 s with 401 points
x = t.*exp(-t).*cos(2*pi*4*t); %Define a vector of x values
plot(t,x); %Plot x vs. t
xlabel(Time (s)); %Label time axis
ylabel(Amplitude); %Label amplitude axis

4.1.1 Simple plotting commands
The simple 2D plotting commands include
plot Plot in linear coordinates as a continuous function
stem Plot in linear coordinates as discrete samples
loglog Logarithmic x and y axes
semilogx Linear y and logarithmic x axes
semilogy Linear x and logarithmic y axes
bar Bar graph
errorbar Error bar graph
hist Histogram
polar Polar coordinates
4.1.2 Customization of plots
There are many commands used to customize plots by annotations, titles, axes labels, etc.
A few of the most frequently used commands are
xlabel Labels x-axis
ylabel Labels y-axis
title Puts a title on the plot
grid Adds a grid to the plot
axis Allows changing the x and y axes
figure Create a gure for plotting
hold on Allows multiple plots to be superimposed on the same
axes
hold off Release hold on current plot
close(n) Close gure number n
subplot(a,b,c) Create an a b matrix of plots with c the current
gureorient Specify orientation of a gure.
4.2 MATLAB Graphics
MATLAB has several high-level graphical routines. They allow a user to create various graphical
objects including two- and three-dimensional graphs, graphical user interfaces (GUIs), movies, to

36

mention the most important ones. For the comprehensive presentation of the MATLAB graphics the
interested reader is referred to [2].
Before we begin discussion of graphical tools that are available in MATLAB I recommend that you
will run a couple of demos that come with MATLAB. In the Command Window click on Help and
next select Examples and Demos. Chose Visualization, and next select 2-D Plots. You will be
presented with several buttons. Select Line and examine the m-file below the graph. It should give
you some idea about computer code needed for creating a simple graph. It is recommended that you
examine carefully contents of all m-files that generate the graphs in this demo.
4.2.1 2-D Graphics
Basic function used to create 2-D graphs is the plot function. This function takes a variable number of
input arguments. For the full definition of this function type help plot in the Command Window.
In this example the graph of the rational function () =

1+
,-2 x 2 will be plotted using a variable
number of points on the graph of f(x).
% Script file graph1.
% Graph of the rational function y = x/(1+x^2).
for n=1:2:5
n10 = 10*n;
x = linspace(-2,2,n10);
y = x./(1+x.^2);
plot(x,y,'r')
title(sprintf('Graph %g. Plot based upon n = %g points.' ...
, (n+1)/2, n10))
axis([-2,2,-.8,.8])
xlabel('x')
ylabel('y')
grid
pause(3)
end
Let us analyze contents of this file. The loop for is executed three times. Therefore, three graphs of
the same function will be displayed in the Figure Window. A MATLAB function linspace(a, b, n)
generates a one-dimensional array of n evenly spaced numbers in the interval [a b]. The y-ordinates
of the points to be plotted are stored in the array y. Command plot is called with three arguments: two
arrays holding the x- and the y-coordinates and the string 'r', which describes the color (red) to be
used to paint a plotted curve. You should notice a difference between three graphs created by this file.
There is a significant difference between smoothness of graphs 1 and 3. Based on your visual
observation you should be able to reach the following conclusion: "more points you supply the
smoother graph is generated by the function plot". Function title adds a descriptive information to the
graphs generated by this m-file and is followed by the command sprintf. Note that sprintf takes here
three arguments: the string and names of two variables printed in the title of each graph. To specify
format of printed numbers we use here the construction %g, which is recommended for printing
integers. The command axis tells MATLAB what the dimensions of the box holding the plot are. To
add more information to the graphs created here, we label the x- and the y-axes using commands
xlabel and the ylabel, respectively. Each of these commands takes a string as the input argument.
Function grid adds the grid lines to the graph. The last command used before the closing end is the
pause command. The command pause(n) holds on the current graph for n seconds before continuing,
where n can also be a fraction. If pause is called without the input argument, then the computer waits
to user response. For instance, pressing the Enter key will resume execution of a program. Function
subplot is used to plot of several graphs in the same Figure Window. Here is a slight modification of
the m-file graph1
% Script file graph2.

37

% Several plots of the rational function y = x/(1+x^2)
% in the same window.
k = 0;
for n=1:3:10
n10 = 10*n;
x = linspace(-2,2,n10);
y = x./(1+x.^2);
k = k+1;
subplot(2,2,k)
plot(x,y,'r')
title(sprintf('Graph %g. Plot based upon n = %g points.' ...
, k, n10))
xlabel('x')
ylabel('y')
axis([-2,2,-.8,.8])
grid
pause(3);
end
The command subplot is called here with three arguments. The first two tell MATLAB that a 2-by-2
array consisting of four plots will be created. The third parameter is the running index telling
MATLAB which subplot is currently generated.
graph2
















Using command plot you can display several curves in the same Figure Window.
We will plot two ellipses
( 3)
2
36
+
( + 2)
2
81
= 1
( 7)
2
4
+
( 8)
2
36
= 1
using command plot

% Script file graph3.
% Graphs of two ellipses
% x(t) = 3 + 6cos(t), y(t) = -2 + 9sin(t) as x=a+rcos(theta) and
% y=a+rsin(theta)are
% and
% x(t) = 7 + 2cos(t), y(t) = 8 + 6sin(t).
t = 0:pi/100:2*pi;
x1 = 3 + 6*cos(t);
y1 = -2 + 9*sin(t);

38

x2 = 7 + 2*cos(t);
y2 = 8 + 6*sin(t);
h1 = plot(x1,y1,'r',x2,y2,'b');
set(h1,'LineWidth',1.25)
axis('square')
xlabel('x')
h = get(gca,'xlabel');
set(h,'FontSize',12)
set(gca,'XTick',-4:10)
ylabel('y')
h = get(gca,'ylabel');
set(h,'FontSize',12)
set(gca,'YTick',-12:2:14)
title('Graphs of (x-3)^2/36+(y+2)^2/81 = 1 and (x-7)^2/4+(y-8)^2/36 =1.')
h = get(gca,'Title');
set(h,'FontSize',12)
grid
In this file we use several new MATLAB commands. They are used here to enhance the readability of
the graph. Let us now analyze the computer code contained in the m-file graph3. First of all, the
equations of ellipses in rectangular coordinates are transformed to parametric equations. This is a
convenient way to plot graphs of equations in the implicit form. The points to be plotted, and
smoothed by function plot, are defined in the first five lines of the file. I do not count here the
comment lines and the blank lines. You can plot both curves using a single plot command. Moreover,
you can select colors of the curves. They are specified as strings (see line 6). MATLAB has several
colors you can use to plot graphs:
y yellow
m magenta
c cyan
r red
g green
b blue
w white
k black
Note that the command in line 6 begins with h1 = plot Variable h1 holds an information about the
graph you generate and is called the handle graphics. Command set used in the next line allows a user
to manipulate a plot. Note that this command takes as the input parameter the variable h1. We change
thickness of the plotted curves from the default value to a width of our choice, namely 1.25. In the
next line we use command axis to customize plot. We chose option 'square' to force axes to have
square dimensions. Other available options are:
'equal', 'normal', 'ij', 'xy', and 'tight'. To learn more about these options use MATLAB's help.

If function axis is not used, then the circular curves are not necessarily circular. To justify this let us
plot a graph of the unit circle of radius 1 with center at the origin
t = 0:pi/100:2*pi;
x = cos(t);
y = sin(t);
plot(x,y)






39







Another important MATLAB function used in the file under discussion is named get (see line 10). It
takes as the first input parameter a variable named gca = get current axis. It should be obvious to you,
that the axis targeted by this function is the x-axis. Variable h = get(gca, ) is the graphics handle
of this axis. With the information stored in variable h, we change the font size associated with the x-
axis using the 'FontSize' string followed by a size of the font we wish to use. Invoking function set in
line 12, we will change the tick marks along the x-axis using the 'XTick' string followed by the array
describing distribution of marks. You can comment out temporarily line 12 by adding the percent sign
% before the word set to see the difference between the default tick marks and the marks generated
by the command in line 12. When you are done delete the percent sign you typed in line 12 and click
on Save from the File
menu in the MATLAB Editor/Debugger. Finally, you can also make changes in the title of your
plot. For instance, you can choose the font size used in the title. This is accomplished here by using
function set. It should be obvious from the short discussion presented here that two MATLAB
functions get and set are of great importance in manipulating graphs.

Graphs of the ellipses in question are shown
graph3















MATLAB has several functions designed for plotting specialized 2-D graphs. A partial list of these
functions is included here fill, polar, bar, barh, pie, hist, compass, errorbar, stem, and feather.
In this example function fill is used to create a well-known object
n = -6:6;
x = sin(n*pi/6);
y = cos(n*pi/6);
fill(x, y, 'r')
axis('square')
title('Graph of the n-gone')
text(-0.45,0,'What is a name of this object?')
Function in question takes three input parameters - two arrays, named here x and y. They hold the x-
and y-coordinates of vertices of the polygon to be filled. Third parameter is the user-selected color to
be used to paint the object. A new command that appears in this short code is the text command. It is

40

used to annotate a text. First two input parameters specify text location. Third input parameter is a
text, which will be added
to the plot.
Graph of the filled object
that is generated by
this code is displayed
below


















4.2.2 3-D Graphics
MATLAB has several built-in functions for plotting three-dimensional objects. In this subsection we
will deal mostly with functions used to plot curves in space (plot3), mesh surfaces (mesh), surfaces
(surf) and contour plots (contour). Also, two functions for plotting special surfaces, sphere and
cylinder will be discussed briefly. I recommend that any time you need help with the 3-D graphics
you should type help graph3d in the Command Window to learn more about various functions that
are available for plotting three-dimensional objects.
Let r(t) = < t cos(t), t sin(t), t >, -10t10, be the space curve. We plot its graph over the indicated
interval using function plot3
% Script file graph4.
% Curve r(t) = < t*cos(t), t*sin(t), t >.
t = -10*pi:pi/100:10*pi;
x = t.*cos(t);
y = t.*sin(t);
h = plot3(x,y,t);
set(h,'LineWidth',1.25)
title('Curve u(t) = < t*cos(t), t*sin(t), t >')
h = get(gca,'Title');
set(h,'FontSize',12)
xlabel('x')
h = get(gca,'xlabel');
set(h,'FontSize',12)
ylabel('y')
h = get(gca,'ylabel');
set(h,'FontSize',12)
zlabel('z')

41

h = get(gca,'zlabel');
set(h,'FontSize',12)
grid
Function plot3 is used in line 4. It takes three input parameters arrays holding coordinates of points
on the curve to be plotted. Another new command in this code is the zlabel command (see line 4 from
the bottom). Its meaning is self-explanatory.
graph4












Function mesh is intended for plotting graphs of the 3-D mesh surfaces. Before we begin to work
with this function, another function meshgrid should be introduced. This function generates two two-
dimensional arrays for 3-D plots. Suppose that one wants to plot a mesh surface over the grid that is
defined as the Cartesian product of two sets
x = [0 1 2];
y = [10 12 14];
The meshgrid command applied to the arrays x and y creates two matrices
[xi, yi] = meshgrid(x,y)

xi =

0 1 2
0 1 2
0 1 2


yi =

10 10 10
12 12 12
14 14 14
Note that the matrix xi contains replicated rows of the array x while yi contains replicated columns of
y. The z-values of a function to be plotted are computed from arrays xi and yi. In this example we will
plot the hyperbolic paraboloid z = y2 x2 over the square 1 x 1,-1 y 1
x = -1:0.05:1;

42

y = x;
[xi, yi] = meshgrid(x,y);
zi = yi.^2 xi.^2;
mesh(xi, yi, zi)
axis off

To plot the graph of the mesh surface together with the contour plot beneath the plotted surface use
function meshc
meshc(xi, yi, zi)
axis off









Function surf is used to visualize data as a shaded surface. Computer code in the m-file graph5
should help you to learn some finer points of the 3-D graphics in MATLAB
% Script file graph5.
% Surface plot of the hyperbolic paraboloid z = y^2 - x^2
% and its level curves.
x = -1:.05:1;
y = x;
[xi,yi] = meshgrid(x,y);
zi = yi.^2 - xi.^2;
surfc(xi,yi,zi)
colormap copper
shading interp
view([25,15,20])
grid off
title('Hyperbolic paraboloid z = y^2 x^2')
h = get(gca,'Title');

43

set(h,'FontSize',12)
xlabel('x')
h = get(gca,'xlabel');
set(h,'FontSize',12)
ylabel('y')
h = get(gca,'ylabel');
set(h,'FontSize',12)
zlabel('z')
h = get(gca,'zlabel');
set(h,'FontSize',12)
pause(5)
figure
contourf(zi), hold on, shading flat
[c,h] = contour(zi,'k-'); clabel(c,h)
title('The level curves of z = y^2 - x^2.')
h = get(gca,'Title');
set(h,'FontSize',12)
xlabel('x')
h = get(gca,'xlabel');
set(h,'FontSize',12)
ylabel('y')
h = get(gca,'ylabel');
set(h,'FontSize',12)
graph5























44







There are several new commands used in this file. On line 5 (again, I do not count the blank lines and
the comment lines) a command surfc is used. It plots a surface together with the level lines beneath.
Unlike the command surfc the command surf plots a surface only without the level curves. Command
colormap is used in line 6 to paint the surface using a user-supplied colors. If the command
colormap is not added, MATLAB uses default colors. Here is a list of color maps that are available in
MATLAB

hsv - hue-saturation-value color map
hot - black-red-yellow-white color map
gray - linear gray-scale color map
bone - gray-scale with tinge of blue color map
copper - linear copper-tone color map
pink - pastel shades of pink color map
white - all white color map
flag - alternating red, white, blue, and black color map
lines - color map with the line colors
colorcube - enhanced color-cube color map
vga - windows colormap for 16 colors
jet - variant of HSV
prism - prism color map
cool - shades of cyan and magenta color map
autumn - shades of red and yellow color map
spring - shades of magenta and yellow color map
winter - shades of blue and green color map
summer - shades of green and yellow color map

Command shading (see line 7) controls the color shading used to paint the surface. Command in
question takes one argument. The following
shading flat sets the shading of the current graph to flat
shading interp sets the shading to interpolated
shading faceted sets the shading to faceted, which is the default.
are the shading options that are available in MATLAB.

Command view (see line 8) is the 3-D graph viewpoint specification. It takes a three-dimensional
vector, which sets the view angle in Cartesian coordinates.

We will now focus attention on commands on lines 23 through 25. Command figure prompts
MATLAB to create a new Figure Window in which the level lines will be plotted. In order to
enhance the graph, we use command contourf instead of contour. The former plots filled contour
lines while the latter doesn't. On the same line we use command hold on to hold the current plot and
all axis properties so that subsequent graphing commands add to the existing graph. First command on
line 25 returns matrix c and graphics handle h that are used as the input parameters for the function
clabel, which adds height labels to the current contour plot.


45

Due to the space limitation we cannot address here other issues that are of interest for programmers
dealing with the 3-D graphics in MATLAB. To learn more on this subject the interested reader is
referred to [1-3] and [5].

4.2.3 Reference
[6] D. Hanselman and B. Littlefield, Mastering MATLAB 5. A Comprehensive Tutorial
andReference, Prentice Hall, Upper Saddle River, NJ, 1998.
[7] P. Marchand, Graphics and GUIs with MATLAB, Second edition, CRC Press, Boca
Raton,1999.
[8] K. Sigmon, MATLAB Primer, Fifth edition, CRC Press, Boca Raton, 1998.
[9] Using MATLAB, Version 5, The MathWorks, Inc., 1996.
[10] Using MATLAB Graphics, Version 5, The MathWorks, Inc., 1996.
[11] Matlab tutorial by Edward Neuman

4.2.4 Problems

1. Write a script file Problem 1 to plot, in the same window, graphs of two parabolas y = x
2
and x =
y2, where 1 x 1. Label the axes, add a title to your graph and use command grid. To improve
readability of the graphs plotted add a legend. MATLAB has a command legend. To learn more
about this command type help legend in the Command Window and press Enter or Return key.

2. Write MATLAB function eqtri(a, b) that plots the graph of the equilateral triangle with two
vertices at (a,a) and (b,a). Third vertex lies above the line segment that connects points (a, a) and
(b, a). Use function fill to paint the triangle using a color of your choice.

3. In this exercise you are to plot graphs of the Chebyshev polynomial Tn(x) and its first order
derivative over the interval [-1, 1]. Write MATLAB function plotChT(n) that takes as the input
parameter the degree n of the Chebyshev polynomial. Use functions ChebT and derp, included in
pervious Lab, to compute coefficients of Tn(x) and T'n(x), respectively. Evaluate both, the
polynomial and its first order derivative at x = linspace(-1, 1) using MATLAB function polyval.
Add a meaningful title to your graph. In order to improve readability of your graph you may wish
to add a descriptive legend. Here is a sample output and formula of polynomial is given in
previous Lab
plotChT(5)















46

4. Use function sphere to plot the graph of a sphere of radius r with center at (a, b, c). Use
MATLAB function axis with an option 'equal'. Add a title to your graph and save your computer
code as the MATLAB function sph(r, a, b,
c).

5. Write MATLAB function ellipsoid(x0,
y0, z0, a, b, c) that takes coordinates (x0,
y0, z0) of the center of the ellipsoid with
semiaxes (a, b, c) and plots its graph. Use
MATLAB functions sphere and surf. Add
a meaningful title to your graph and use
function axis('equal').

6. In this exercise you are to plot a graph of the
two-sided cone, with vertex at the origin,
and the-axis as the axis of symmetry. Write
MATLAB function cone(a, b), where the input parameters a and b stand for the radius of the
lower and upper base, respectively. Use MATLAB functions cylinder and surf to plot a cone in
question. Add a title to your graph and use function shading with an argument of your choice. A
sample output is shown below
cone(1, 2)
















7. The space curve r(t) = < cos(t)sin(4t), sin(t)sin(4t), cos(4t) >, 0 t 2, lies on the surface of
the unit sphere x2 + y2 + z2 = 1. Write MATLAB script file curvsph that plots both the curve and
the sphere in the same window. Add a meaningful title to your graph. Use MATLAB functions
colormap and shading with arguments of your choice. Add the view([150 125 50]) command.



47

Lab 5: Linear Algebra using MATLAB
One of the nice features of MATLAB is its ease of computations with vectors and matrices. In this
tutorial the following topics are discussed: vectors and matrices in MATLAB, solving systems of
linear equations, the inverse of a matrix, determinants, vectors in n-dimensional Euclidean space,
linear transformations, real vector spaces and the matrix eigenvalue problem. Applications of linear
algebra to the curve fitting, message coding and computer graphics are also included.
5.1 Special character and MATLAB functions used in LAB4
For the student's convenience we include lists of special characters and MATLAB functions that are
used in this Lab.



Function Description
acos Inverse cosine
axis Control axis scaling and appearance
char Create character array
chol Cholesky factorization
cos Cosine function
cross Vector cross product
det Determinant
diag Diagonal matrices and diagonals of
a matrix
double Convert to double precision
eig Eigenvalues and eigenvectors
eye Identity matrix
fill Filled 2-D polygons
fix Round towards zero
fliplr Flip matrix in left/right direction
flops Floating point operation count
grid Grid lines
hadamard Hadamard matrix
hilb Hilbert matrix
hold Hold current graph

48

inv Matrix inverse
isempty True for empty matrix
legend Graph legend
length Length of vector
linspace Linearly spaced vector
logical Convert numerical values to logical
magic Magic square
max Largest component
min Smallest component
norm Matrix or vector norm
null Null space
num2cell Convert numeric array into cell
array
num2str Convert number to string
ones Ones array
pascal Pascal matrix
plot Linear plot
poly Convert roots to polynomial
polyval Evaluate polynomial
rand Uniformly distributed random
numbers
randn Normally distributed random
numbers
rank Matrix rank
reff Reduced row echelon form
rem Remainder after division
reshape Change size
roots Find polynomial roots
sin Sine function
size Size of matrix
sort Sort in ascending order
subs Symbolic substitution
sym Construct symbolic numbers and
variables
tic Start a stopwatch timer
title Graph title
toc Read the stopwatch timer
toeplitz Tioeplitz matrix
tril Extract lower triangular part
triu Extract upper triangular part
vander Vandermonde matrix
varargin Variable length input argument list
zeros Zeros array
5.1.1 Vector and matrices in MATLAB
The purpose of this section is to demonstrate how to create and transform vectors and matrices in
MATLAB.
This command creates a row vector
a = [1 2 3]
a =
1 2 3
Column vectors are inputted in a similar way, however, semicolons must separate the components of a
vector
b = [1;2;3]
b =

49

1
2
3
The quote operator ' is used to create the conjugate transpose of a vector (matrix) while the dotquote
operator .' creates the transpose vector (matrix). To illustrate this let us form a complex vector a +
i*b' and next apply these operations to the resulting vector to obtain
(a+i*b')'
ans =
1.0000 - 1.0000i
2.0000 - 2.0000i
3.0000 - 3.0000i
While
(a+i*b').'
ans =
1.0000 + 1.0000i
2.0000 + 2.0000i
3.0000 + 3.0000i
Command length returns the number of components of a vector
length(a)
ans =
3
The dot operator. plays a specific role in MATLAB. It is used for the component wise application of
the operator that follows the dot operator
a.*a
ans =
1 4 9
The same result is obtained by applying the power operator ^ to the vector a
a.^2
ans =
1 4 9
Componentwise division of vectors a and b can be accomplished by using the backslash operator \
together with the dot operator .
a.\b'
ans =
1 1 1
For the purpose of the next example let us change vector a to the column vector
a = a'
a =
1
2
3
The dot product and the outer product of vectors a and b are calculated as follows
dotprod = a'*b
dotprod =
14
outprod = a*b'
outprod =
1 2 3
2 4 6
3 6 9
The cross product of two three-dimensional vectors is calculated using command cross. Let the vector
a be the same as above and let

50

b = [-2 1 2];
Note that the semicolon after a command avoids display of the result. The cross product of a and b is
cp = cross(a,b)
cp =
1 -8 5
The cross product vector cp is perpendicular to both a and b
[cp*a cp*b']
ans =
0 0
We will now deal with operations on matrices. Addition, subtraction, and scalar multiplication are
defined in the same way as for the vectors.
This creates a 3-by-3 matrix
A = [1 2 3;4 5 6;7 8 10]
A =
1 2 3
4 5 6
7 8 10
Note that the semicolon operator ; separates the rows. To extract a sub matrix B consisting of rows 1
and 3 and columns 1 and 2 of the matrix A do the following
B = A([1 3], [1 2])
B =
1 2
7 8
To interchange rows 1 and 3 of A use the vector of row indices together with the colon operator
C = A([3 2 1],:)
C =
7 8 10
4 5 6
1 2 3
The colon operator : stands for all columns or all rows. For the matrix A from the last example the
following command
A(:)
ans =
1
4
7
2
5
8
3
6
10
creates a vector version of the matrix A. We will use this operator on several occasions. To delete a
row (column) use the empty vector operator [ ]
A(:, 2) = []
A =
1 3
4 6
7 10
Second column of the matrix A is now deleted. To insert a row (column) we use the technique for
creating matrices and vectors
A = [A(:,1) [2 5 8]' A(:,2)]
A =
1 2 3
4 5 6
7 8 10
Matrix A is now restored to its original form.

51

Using MATLAB commands one can easily extract those entries of a matrix that satisfy an imposed
condition. Suppose that one wants to extract all entries of that are greater than one. First, we define a
new matrix A
A = [-1 2 3;0 5 1]
A =
-1 2 3
0 5 1
Command A > 1 creates a matrix of zeros and ones
A > 1
ans =
0 1 1
0 1 0
with ones on these positions where the entries of A satisfy the imposed condition and zeros
everywhere else. This illustrates logical addressing in MATLAB. To extract those entries of the
matrix A that are greater than one we execute the following command
A(A > 1)
ans =
2
5
3
The dot operator . works for matrices too. Let now
A = [1 2 3; 3 2 1] ;
The following command
A.*A
ans =
1 4 9
9 4 1
computes the entry-by-entry product of A with A. However, the following command
A*A
??? Error using ==> *
Inner matrix dimensions must agree.
generates an error message.
Function diag will be used on several occasions. This creates a diagonal matrix with the diagonal
entries stored in the vector d
d = [1 2 3];
D = diag(d)
D =
1 0 0
0 2 0
0 0 3
To extract the main diagonal of the matrix D we use function diag again to obtain
d = diag(D)
d =
1
2
3
What is the result of executing of the following command?
diag(diag(d));
In some problems that arise in linear algebra one needs to calculate a linear combination of several
matrices of the same dimension. In order to obtain the desired combination both the coefficients and
the matrices must be stored in cells. In MATLAB a cell is inputted using curly braces{ }. This
c = {1,-2,3}
c =
[1] [-2] [3]
is an example of the cell. Function lincomb will be used later on in this tutorial.
function M = lincomb(v,A)

52

% Linear combination M of several matrices of the same size.
% Coefficients v = {v1,v2,,vm} of the linear combination and the
% matrices A = {A1,A2,...,Am} must be inputted as cells.
m = length(v);
[k, l] = size(A{1});
M = zeros(k, l);
for i = 1:m
M = M + v{i}*A{i};
End
5.2 Solving system of linear equations
MATLAB has several tool needed for computing a solution of the system of linear equations. Let A
be an m-by-n matrix and let b be an m-dimensional (column) vector. To solve the linear system Ax =
b one can use the backslash operator \ , which is also called the left division.
1. Case m = n
In this case MATLAB calculates the exact solution (modulo the roundoff errors) to the system in
question.
Let
A = [1 2 3;4 5 6;7 8 10]
A =
1 2 3
4 5 6
7 8 10
and let
b = ones(3,1);
Then
x = A\b
x =
-1.0000
1.0000
0.0000
In order to verify correctness of the computed solution let us compute the residual vector r
r = b - A*x
r =
1.0e-015 *
0.1110
0.6661
0.2220
Entries of the computed residual r theoretically should all be equal to zero. This example illustrates an
effect of the roundoff errors on the computed solution.
2. Case m > n
If m > n, then the system Ax = b is overdetermined and in most cases system is inconsistent. A
solution to the system Ax = b, obtained with the aid of the backslash operator \ , is the leastsquares
solution.
Let now
A = [2 --1; 1 10; 1 2];
and let the vector of the right-hand sides will be the same as the one in the last example. Then
x = A\b
x =
0.5849
0.0491
The residual r of the computed solution is equal to
r = b - A*x
r =
-0.1208
-0.0755

53

0.3170
Theoretically the residual r is orthogonal to the column space of A. We have
r'*A
ans =
1.0e-014 *
0.1110
0.6994
3. Case m < n
If the number of unknowns exceeds the number of equations, then the linear system is
underdetermined. In this case MATLAB computes a particular solution provided the system is
consistent. Let now
A = [1 2 3; 4 5 6];
b = ones(2,1);
Then
x = A\b
x =
-0.5000
0
0.5000
A general solution to the given system is obtained by forming a linear combination of x with the
columns of the null space of A. The latter is computed using MATLAB function null
z = null(A)
z =
0.4082
-0.8165
0.4082
Suppose that one wants to compute a solution being a linear combination of x and z, with coefficients
1 and 1. Using function lincomb we obtain
w = lincomb({1,-1},{x,z})
w =
-0.9082
0.8165
0.0918
The residual r is calculated in a usual way
r = b - A*w
r =
1.0e-015 *
-0.4441
0.1110
5.2.1 Function rref and its applications
The built-in function rref allows a user to solve several problems of linear algebra. In this section we
shall employ this function to compute a solution to the system of linear equations and also to find the
rank of a matrix. Other applications are discussed in the subsequent sections of this lab.
Function rref takes a matrix and returns the reduced row echelon form of its argument. Syntax of the
rref command is
B = rref(A) or [B, pivot] = rref(A)
The second output parameter pivot holds the indices of the pivot columns.
Let
A = magic(3); b = ones(3,1);
A solution x to the linear system Ax = b is obtained in two steps. First the augmented matrix of
the system is transformed to the reduced echelon form and next its last column is extracted
[x, pivot] = rref([A b])
x =
1.0000 0 0 0.0667
0 1.0000 0 0.0667
0 0 1.0000 0.0667

54

pivot =
1 2 3
x = x(:,4)
x =
0.0667
0.0667
0.0667
The residual of the computed solution is
b - A*x
ans =
0
0
0
Information stored in the output parameter pivot can be used to compute the rank of the matrix A
length(pivot)
ans =
3
5.3 The inverse of a Matrix
MATLAB function inv is used to compute the inverse matrix.
Let the matrix A be defined as follows
A = [1 2 3;4 5 6;7 8 10]
A =

1 2 3
4 5 6
7 8 10
Then
B = inv(A)
B =

-0.6667 -1.3333 1.0000
-0.6667 3.6667 -2.0000
1.0000 -2.0000 1.0000
In order to verify that B is the inverse matrix of A it sufficies to show that A*B = I and B*A = I,
where I is the 3-by-3 identity matrix. We have
A*B
ans =

1.0000 0 -0.0000
0 1.0000 0
0 0 1.0000
In a similar way one can check that B*A = I.
The Pascal matrix, named in MATLAB pascal, has several interesting properties. Let
A = pascal(3)
A =

1 1 1
1 2 3
1 3 6
Its inverse B
B = inv(A)
B =

3.0000 -3.0000 1.0000
-3.0000 5.0000 -2.0000
1.0000 -2.0000 1.0000
is the matrix of integers. The Cholesky triangle of the matrix A is

55

S = chol(A)
S =

1 1 1
0 1 2
0 0 1
Note that the upper triangular part of S holds the binomial coefficients. One can verify easily that
A = S'*S.
Function rref can also be used to compute the inverse matrix. Let A is the same as above. We create
first the augmented matrix B with A being followed by the identity matrix of the same size as A.
Running function rref on the augmented matrix and next extracting columns four through six of the
resulting matrix, we obtain
B = rref([A eye(size(A))]);
B = B(:, 4:6)
B =

3 -3 1
-3 5 -2
1 -2 1
To verify this result, we compute first the product A *B
A*B
ans =

1 0 0
0 1 0
0 0 1
and next B*A
B*A
ans =

1 0 0
0 1 0
0 0 1
This shows that B is indeed the inverse matrix of A.

5.3.1 Determinants
In some applications of linear algebra knowledge of the determinant of a matrix is required.
MATLAB built-in function det is designed for computing determinants.
Let
A = magic(3);
Determinant of A is equal to
det(A)
ans =
-360
One of the classical methods for computing determinants utilizes a cofactor expansion. For more
details, see e.g., [2], pp. 103-114.
Function ckl = cofact(A, k, l) computes the cofactor ckl of the akl entry of the matrix A
function ckl = cofact(A,k,l)
% Cofactor ckl of the a_kl entry of the matrix A.
[m,n] = size(A);
if m ~= n
error('Matrix must be square')
end
B = A([1:k-1,k+1:n],[1:l-1,l+1:n]);
ckl = (-1)^(k+l)*det(B);
Function d = mydet(A) implements the method of cofactor expansion for computing determinants

56

function d = mydet(A)
% Determinant d of the matrix A. Function cofact must be
% in MATLAB's search path.
[m,n] = size(A);
if m ~= n
error('Matrix must be square')
end
a = A(1,:);
c = [];
for l=1:n
c1l = cofact(A,1,l);
c = [c;c1l];
end
d = a*c;
Let us note that function mydet uses the cofactor expansion along the row 1 of the matrix A. Method
of cofactors has a high computational complexity. Therefore it is not recommended for computations
with large matrices. Its is included here for pedagogical reasons only. To measure a computational
complexity of two functions det and mydet we will use MATLAB built-in function flops. It counts
the number of floating-point operations (additions, subtractions, multiplications and divisions). Let
A = rand(25);
be a 25-by-25 matrix of uniformly distributed random numbers in the interval ( 0, 1 ). Using
function det we obtain
flops(0)
det(A)
ans =
-0.1867
flops
ans =
10100
For comparison, a number of flops used by function mydet is
flops(0)
mydet(A)
ans =
-0.1867
flops
ans =
223350
The adjoint matrix adj(A) of the matrix A is also of interest in linear algebra (see, e.g., [2], p.108).
function B = adj(A)
% Adjoint matrix B of the square matrix A.
[m,n] = size(A);
if m ~= n
error('Matrix must be square')
end
B = [];
for k = 1:n
for l=1:n
B = [B;cofact(A,k,l)];
end
end
B = reshape(B,n,n);
The adjoint matrix and the inverse matrix satisfy the equation
A
-1
= adj(A)/det(A)
(see [2], p.110 ). Due to the high computational complexity this formula is not recommended for
computing the inverse matrix.


57

5.4 The matrix Eigen value problem
MATLAB function eig is designed for computing the eigenvalues and the eigenvectors of the matrix
A. Its syntax is shown below
[V, D] = eig(A)
The eigenvalues of A are stored as the diagonal entries of the diagonal matrix D and the associated
eigenvectors are stored in columns of the matrix V.
Let
A = pascal(3);
Then
[V, D] = eig(A)
V =
-0.5438 -0.8165 0.1938
0.7812 -0.4082 0.4722
-0.3065 0.4082 0.8599
D =
0.1270 0 0
0 1.0000 0
0 0 7.8730
Clearly, matrix A is diagonalizable. The eigenvalue-eigenvector decomposition A = VDV
-1
of A is
calculated as follows
V*D/V
ans =
1.0000 1.0000 1.0000
1.0000 2.0000 3.0000
1.0000 3.0000 6.0000
Note the use of the right division operator / instead of using the inverse matrix function inv. This is
motivated by the fact that computation of the inverse matrix takes longer than the execution of the
right division operation.

The characteristic polynomial of a matrix is obtained by invoking the function poly.
Let
A = magic(3);
be the magic square. In this example the vector chpol holds the coefficients of the characteristic
polynomial of the matrix A. Recall that a polynomial is represented in MATLAB by its
coefficients that are ordered by descending powers
chpol = poly(A)
chpol =
1.0 -15.0000 -24.0000 360.0000
The eigenvalues of A can be computed using function roots
eigenvals = roots(chpol)
eigenvals =
15.0000
-4.8990
4.8990
This method, however, is not recommended for numerical computing the eigenvalues of a matrix.
There are several reasons for which this approach is not used in numerical linear algebra.

The Caley-Hamilton Theorem states that each matrix satisfies its characteristic equation, i.e.,
chpol(A) = 0, where the last zero stands for the matrix of zeros of the appropriate dimension. We use
function lincomb to verify this result
Q = lincomb(num2cell(chpol), {A^3, A^2, A, eye(size(A))})
Q =
1.0e-012 *
-0.5684 -0.5542 -0.4832

58

-0.5258 -0.6253 -0.4547
-0.5116 -0.4547 -0.6821
5.5 Application of linear algebra
List of applications of methods of linear algebra is long and impressive. Areas that relay heavily on
the methods of linear algebra include the data fitting, mathematical statistics, linear programming,
computer graphics, cryptography, and economics, to mention the most important ones. Applications
discussed in this section include the data fitting, coding messages, and computer graphics.

5.5.1 Data fitting
In many problems that arise in science and engineering one wants to fit a discrete set of points in the
plane by a smooth curve or function. A typical choice of a smoothing function is a polynomial of a
certain degree. If the smoothing criterion requires minimization of the 2-norm, then one has to solve
the least-squares approximation problem. Function fit takes three arguments, the degree of the
approximating polynomial, and two vectors holding the x- and the y- coordinates of points to be
approximated. On the output, the coefficients of the least-squares polynomials are returned. Also, its
graph and the plot of the data points are generated.

function c = fit(n, t, y)
% The least-squares approximating polynomial of degree n (n>=0).
% Coordinates of points to be fitted are stored in the column vectors
% t and y. Coefficients of the approximating polynomial are stored in
% the vector c. Graphs of the data points and the least-squares
% approximating polynomial are also generated.
if ( n >= length(t))
error('Degree is too big')
end
v = fliplr(vander(t));
v = v(:,1:(n+1));
c = v\y;
c = fliplr(c');
x = linspace(min(t),max(t));
w = polyval(c, x);
plot(t,y,'ro',x,w);
title(sprintf('The least-squares polynomial of degree n = %2.0f',n))
legend('data points','fitting polynomial')

To demonstrate functionality of this code we generate first a set of points in the plane. Our goal is to
fit ten evenly spaced points with the y-ordinates being the values of the function y = sin(2t) at these
points

t = linspace(0, pi/2, 10); t = t';
y = sin(2*t);

We will fit the data by a polynomial of degree at most three
c = fit(3, t, y)
c =
-0.0000 -1.6156 2.5377 -0.0234

59


5.5.2 Coded messages
Some elementary tools of linear algebra can be used to code and decode messages. A typical message
can be represented as a string. The following 'coded message' is an example of the string in
MATLAB. Strings in turn can be converted to a sequence of positive integers using MATLAB's
function double. To code a transformed message multiplication by a nonsingular matrix is used.
Process of decoding messages can be viewed as the inverse process to the one described earlier. This
time multiplication by the inverse of the coding matrix is applied and next MATLAB's function char
is applied to the resulting sequence to recover the original message. Functions code and decode
implement these steps.

function B = code(s, A)
% String s is coded using a nonsingular matrix A.
% A coded message is stored in the vector B.
p = length(s);
[n,n] = size(A);
b = double(s);
r = rem(p,n);
if r ~= 0
b = [b zeros(1,n-r)]';
end
b = reshape(b,n,length(b)/n);
B = A*b;
B = B(:)';
function s = dcode(B, A)
% Coded message, stored in the vector B, is
% decoded with the aid of the nonsingular matrix A
% and is stored in the string s.
[n,n]= size(A);
p = length(B);
B = reshape(B,n,p/n);
d = A\B;
s = char(d(:)');
A message to be coded is
s = 'Linear algebra is fun';
As a coding matrix we use the Pascal matrix
A = pascal(4);

60

This codes the message s
B = code(s,A)
B =

Columns 1 through 5
392 1020 2061 3616 340
Columns 6 through 10
809 1601 2813 410 1009
Columns 11 through 15
2003 3490 348 824 1647
Columns 16 through 20
2922 366 953 1993 3603
Columns 21 through 24
110 110 110 110
To decode this message we have to work with the same coding matrix A
dcode(B,A)
ans =
Linear algebra is fun
5.5.3 Computer graphics
Linear algebra provides many tools that are of interest for computer programmers especially for those
who deal with the computer graphics. Once the graphical object is created one has to transform it to
another object. Certain plane and/or space transformations are linear. Therefore they can be realized
as the matrix-vector multiplication. For instance, the reflections, translations, rotations all belong to
this class of transformations. A computer code provided below deals with the plane rotations in the
counter clockwise direction. Function rot2d takes a planar object represented by two vectors x and y
and returns its image. The angle of rotation is supplied in the degree measure.

function [xt, yt] = rot2d(t, x, y)
% Rotation of a two-dimensional object that is represented by two
% vectors x and y. The angle of rotation t is in the degree measure.
% Transformed vectors x and y are saved in xt and yt, respectively.
t1 = t*pi/180;
r = [cos(t1) -sin(t1);sin(t1) cos(t1)];
x = [x x(1)];
y = [y y(1)];
hold on
grid on
axis equal
fill(x, y,'b')
z = r*[x;y];
xt = z(1,:);
yt = z(2,:);
fill(xt, yt,'r');
title(sprintf('Plane rotation through the angle of %3.2f degrees',t))
hold off
Vectors x and y
x = [1 2 3 2]; y = [3 1 2 4];
are the vertices of the parallelogram. We will test function rot2d on these vectors using as the
angle of rotation t = 75.
[xt, yt] = rot2d(75, x, y)
xt =
-2.6390 -0.4483 -1.1554 -3.3461 -2.6390
yt =
1.7424 2.1907 3.4154 2.9671 1.7424

61


The right object is the original parallelogram while the left one is its image.

5.5.4 References
[1] B.D. Hahn, Essential MATLAB for Scientists and Engineers, John Wiley & Sons, New York,
NY, 1997.
[2] D.R. Hill and D.E. Zitarelli, Linear Algebra Labs with MATLAB, Second edition, Prentice
Hall, Upper Saddle River, NJ, 1996.
[3] B. Kolman, Introductory Linear Algebra with Applications, Sixth edition, Prentice Hall,
Upper Saddle River, NJ, 1997.
[4] R.E. Larson and B.H. Edwards, Elementary Linear Algebra, Third edition, D.C. Heath and
Company, Lexington, MA, 1996.
[5] S.J. Leon, Linear Algebra with Applications, Fifth edition, Prentice Hall, Upper Saddle River,
NJ, 1998.
[6] G. Strang, Linear Algebra and Its Applications, Second edition, Academic Press, Orlando,
FL, 1980.

5.5.5 Problems
In Problems 1 12 you cannot use loops for and/or while.
1. Create a ten-dimensional row vector whose all components are equal 2. You cannot enter number
2 more than once.
2. Given a row vector a = [1 2 3 4 5]. Create a column vector b that has the same components as the
vector a but they must bestored in the reversed order.
3. MATLAB built-in function sort(a) sorts components of the vector a in the ascending order.Use
function sort to sort components of the vector a in the descending order.
4. To find the largest (smallest) entry of a vector you can use function max (min). Suppose that
these functions are not available. How would you calculate
a. the largest entry of a vector ?
b. the smallest entry of a vector?
5. Suppose that one wants to create a vector a of ones and zeros whose length is equal to 2n ( n = 1,
2, ). For instance, when n = 3, then a = [1 0 1 0 1 0]. Given value of n create a vector a with
the desired property.

62

6. Let a be a vector of integers.
a. Create a vector b whose all components are the even entries of the vector a.
b. Repeat part (a) where now b consists of all odd entries of the vector a.
c. Hint: Function logical is often used to logical tests. Another useful function you may
consider to use is rem(x, y) - the remainder after division of x by y.
7. Given two nonempty row vectors a and b and two vectors ind1and ind2 with length(a) =
length(ind1) and length(b) = length(ind2). Components of ind1 and ind2 are positive integers.
Create a vector c whose components are those of vectors a and b. Their indices are determined by
vectors ind1 and ind2, respectively.
8. Using function rand, generate a vector of random integers that are uniformly distributed in the
interval (2, 10). In order to insure that the resulting vector is not empty begin with a vector that
has a sufficient number of components.
Hint: Function fix might be helpful. Type help fix in the Command Window to learn more about
this function.
9. Let A be a square matrix. Create a matrix B whose entries are the same as those of A except the
entries along the main diagonal. The main diagonal of the matrix B should consist entirely of
ones.
10. Let A be a square matrix. Create a tridiagonal matrix T whose subdiagonal, main diagonal, and
the superdiagonal are taken from the matrix A.
Hint: You may wish to use MATLAB functions triu and tril. These functions take a second
optional argument. To learn more about these functions use MATLAB's help.
11. In this exercise you are to test a square matrix A for symmetry. Write MATLAB function s =
issymm(A) that takes a matrix A and returns a number s. If A is symmetric, then s = 1, otherwise
s = 0.
12. Let A be an m-by-n and let B be an n-by-p matrices. Computing the product C = AB requires
mnp multiplications. If either A or B has a special structure, then the number of multiplications
can be reduced drastically. Let A be a full matrix of dimension m-by-n and let B be an upper
triangular matrix of dimension n-by-n whose all nonzero entries are equal to one. The product AB
can be calculated without using a single multiplication. Write an algorithm for computing the
matrix product C = A*B that does not require multiplications.
Test your code with the following matrices A = pascal(3) and B = triu(ones(3)).
13. Given square invertible matrices A and B and the column vector b. Assume that the matrices A
and B and the vector b have the same number of rows. Suppose that one wants to solve a linear
system of equations ABx = b. Without computing the matrix-matrix product A*B, find a solution
x to to this system using the backslash operator \.
14. Find all solutions to the linear system Ax = b, where the matrix A consists of rows one through
three of the 5-by-5 magic square
A = magic(5);
A = A(1:3,: )
A =
17 24 1 8 15
23 5 7 14 16
6 13 20 22
and b = ones(3; 1).
15. Determine whether or not the system of linear equations Ax = b, where
A = ones(3, 2); b = [1; 2; 3];
possesses an exact solution x.
16. The purpose of this exercise is to demonstrate that for some matrices the computed solution to Ax
= b can be poor. Define
A = hilb(50); b = rand(50,1);

63

Find the 2-norm of the residual r = A*x b. How would you explain a fact that the computed
norm is essentially bigger than zero?
17. In this exercise you are to use MATLAB function rref to compute the rank of the
followingmatrices:
(a) A = magic(3)
(b) A = magic(4)
(c) A = magic(5)
(d) A = magic(6)
Based on the results of your computations what hypotheses would you formulate about the
rank(magic(n)), when n is odd, when n is even?
18. Use MATLAB to demonstrate that det(A + B) det(A) + det(B) for matrices of your choice.
19. The inverse matrix of a symmetric nonsingular matrix is a symmetric matrix. Check this property
using function inv and a symmetric nonsingular matrix of your choice.
20. Let A be a square matrix. A matrix B is said to be the square root of A if B^2 = A. In MATLAB
the square root of a matrix can be found using the power operator ^. In this exercise you are to
use the eigenvalue-eigenvector decomposition of a matrix find the squareroot of A = [3 3;-2 -2].











64

Lab 6: Introduction to Signals
6.1 Introduction
In this modern world we are surrounded by all kinds of signals in various forms.
Some of the signals are natural, but most of the signals are manmade. Some signals
are necessary (speech), some are pleasant (music), while many are unwanted or
unnecessary in a given situation. In an engineering context, signals are carriers of
information, both useful and unwanted. Therefore extracting or enhancing the useful
information from a mixof conflicting information is a simplest form of signal
processing. More generally, signal processing is anoperation designed for extracting,
enhancing, storing, and transmitting useful information. The distinction between
useful and unwanted information is often subjective as well asobjective. Hence
signal processing tends to be application dependent.
The signals that we encounter in practice are mostly analog signals. Thesesignals,
which vary continuously in time and amplitude, areprocessedusing electrical
networks containing active and passive circuit elements.This approach is known
asanalog signal processing (ASP)--for example,radio and television receivers.

Analog signal: q,(t) Analog signal processor ya(t) :Analog signal

They can also be processed using digital hardware containing adders,multipliers,
and logic elements or using special-purpose microprocessors.However, one needs
toconvert analog signals into a form suitable fordigital hardware. This form of the
signal is called a digital signal. It takesone of the finite numbers of valuesat specific
instances in time, and henceit can be represented by binary numbers, or bits. The
processing of digitalsignals is called DSP;in block diagram form it is represented as:

It appears from the above two approaches to signal processing, analog and digital,
that the DSP approach is the more complicated, containing more components than

65

the simpler looking ASP. Therefore one might ask a question: Why process signals
digitally? The answer lies in many advantages offered by DSP.
6.2 ADVANTAGESOF DSP OVERASP
A major drawback of ASP is its limited scope for performing complicatedsignal
processing applications. This translates into non-flexibility in processingand
complexity in system designs. All of these generally lead toexpensive products. On
the other hand, using a DSP approach, it is possibleto convert an inexpensive
personal computer into a powerful signalprocessor. Some important advantages of
DSP are these:
1. Systems using the DSP approach can be developed using software running on a
general-purpose computer. Therefore DSP is relatively convenient to develop
and test, and the software is portable.
2. DSP operations are based solely on additions and multiplications, leading to
extremely stable processing capability-for example, stability independent of
temperature.
3. DSP operations can easily be modified in real time, often by simple programming
changes, or by reloading of registers.
4. DSP has lower cost due to VLSI technology, which reduces costs of memories,
gates, microprocessors, and so forth.
The principal disadvantage of DSP is the speed of operations, especiallyat very high
frequencies. Primarily due to the above advantages,DSP is nowbecoming a first
choice in many technologies and applications,such asconsumer electronics,
communications, wireless telephones,and medical imaging.
6.2.1 TWOIMPORTANTCATEGORIESOF DSP
Most DSP operations can be categorized as being either signal analysis tasks or
signal filtering tasks as shown below.






6.2.2 Signal analysis
This task deals with the measurement of signal properties. It is generally a frequency-
domain operation. Some of its applications are
- spectrum (frequency and/or phase) analysis

66

- speech recognition
- speaker verification
- target detection
6.2.3 Signal filtering
This task is characterized by the signal in-signal outsituation. The systems that perform
this task are generally called filters. It is usually (but not always) a time domain operation.
Some of the applications are
- removal of unwanted background noise
- removal of interference
- separation of frequency bands
- shaping of the signal spectrum

6.2.4 Signals Representation in MATLAB
Signal Processing in MATLAB is all about processing a discrete-time input signal to
get discrete-time output signal that has more desirable properties. In some
applications the purpose of this processing is merely to extract certain pieces of
information contained in the input signal by applying some processing algorithms.
In other applications the prime objective may be to scrutinize the properties of a
discrete-time system by observing the output of the system against some specific
inputs. Its, therefore, important to first lean how to generate fundamental discrete-
time signals inMATLAB and apply some very basic and primitive operations on
them. In this lab we will generate and plot these signals in time domain. In the
forthcoming lab we will proceed to study their frequency domain representation. So
a discrete time signal is just a sequence of numbers which can be denoted by the
following notation.

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

67

sequence begins at n = 0). An arbitrary infinite-duration sequence cannot be
represented in MATLAB due to the finite memory limitations
6.3 Generation of Sequences
The purpose of this section is to familiarize you with the basic commands in
MATLABfor signal generation and for plotting the generated signal. MATLAB has been
designed to operate on data stored as vectors or matrices. For our purposes, sequences
will be stored as vectors which are actually matrices with single row. Therefore, all
signals are limited to being causal and of finite length.
6.3.1 Unit sample/Impulse sequence
One of the simplest discrete time signals is the unit impulse or unit sample, which is defined
as
[] = {
1 = 0
0 0
}
In Matlabthe function zeros(1,N) generates a row vector of N zeros, which can be used to
implement[]over a finite interval.
>>u = [1 zeros(1, N-1)] where N is the length of sequence.
Command Explained:
The function zeros() is the built-in function in MATLAB that generates zeros. It hasvarious
versions some of which are discussed here.
- zeros(n): generates an nn square matrix of zeros.
- zeros(m,n): generates an mn matrix of zeros.
- zeros(m,n,p): generates an mnp matrix of zeros. Three dimensional arrays can be
assumed as pages of a book.
NOTE: m, n, and p must be non-negative integers. Negative integers are treated aszeros.The
above command actually appends two vectors into one. 1st vector is 1 and thesecond one is
generated by zeros() command. A unit sample sequence of length N delayed in time by M
samples where M N can begenerate in MATLAB by the command
ud = [zeros(1,M) 1 zeros(1, N-M-1)]
Program 1.1 helps understand the implementation of commands discussed above.
% Program 1.1
% Generation of a Unit Sample Sequence
clf; % Clear any existing figure from the current axes
n = -10:20; % Generate a vector from -10 to 20
u = [zeros(1,10) 1 zeros(1,20)]; % Generate the unit sample
sequence
stem(n,u); % Plot the unit sample sequence
xlabel(Time index n);
ylabel(Amplitude);
title(Unit Sample Sequence);
axis([-10 20 0 1.2]);
Q1.1 Run Program 1.1 to generate the unit sample sequence u[n] and sketch it.


68








However, thelogical relation n==0 is an elegant way of implementing []. For example,to
implement
0 n no
[ ]
1 n=no
n no o
=
| |
=
|
\ .


over the n1 n0 n2interval, we will use the following MATLAB function.
function [x, n] =impseq(no,n1,n2)
n= n1:n2;
x=[(n-no)==0]
6.3.2 Unit step sequence
A unit step sequence, denoted by [n], and defined mathematically as
[n] =
1 n>=0
0 n<0
| |
|
\ .

can be generated in the same fashion using ones() command that works in the sameway as
zeros() do with the exception that it fills the generated matrix with 1s insteadof 0s.
Q1.2 What are the purposes of the commands?

clf ------------------------------------------------------------------------------------------------------------
axis ------------------------------------------------------------------------------------------------------------
title ------------------------------------------------------------------------------------------------------------
xlabel ------------------------------------------------------------------------------------------------------------
ylabel ------------------------------------------------------------------------------------------------------------

Q1.3 Modify Program 1.1 to generate a delayed unit sample sequence ud[n] of length80
with a delay of 21 samples. Run the modified program and display the sequence. show
the output plot along with the code to your instructor.

Q1.4 Modify Program 1.1 to generate a unit step sequence s[n]. Run the
modifiedprogram and display the sequence generated. Mention the modification you
done?





69



Q1.5 Modify Program 1.1 to generate a delayed unit step sequence sd[n] with anadvance
of 7 samples. Write done your modified code here.





Q1.6 One more approach to implement this sequence is given below. Explain the difference
between these two codes.
function [x, n] =stepseq(no,n1,n2)
n= n1:n2;
x=[(n-no)>=0]







6.3.3 Sinusoidal sequence
The general form of a periodic trigonometric function is
y = B + Afunction (u+|)
where
A: Amplitude (plotted on y-axis)
B: Offset in amplitude
function: It may be sine, cosine or tangent etc.
: Angular frequency (plotted on x-axis)
: Offset in angular frequency normally known as phase shift.
Program 1.2 generates four sine sequences with different combinations of offsets butthe
same frequency and amplitude.
% Program 1.2
% Generation of sinusoidal sequences
clf;
n = 0:60; % time index
f = 0.1; % linear frequency
A = 2; % Amplitude
dc = 0; % Offset in Amplitude
phase = 0; % Phase Shift
arg = 2*pi*f*n + phase;
x = dc + A*sin(arg);
stem(n,x);

70

axis([0 60 -3 3]);
title('Pure Sinusoidal Sequence');
xlabel('Time index n');
ylabel('Amplitude');
grid;

Q1.6 Modify Program 1.2 to generate four sinusoidal signal on a single screen usingsubplot()
command. The plots must show sinusoidal signals with
1. dc = 0, offset = 0
2. dc = non-zero, offset = zero
3. dc = 0, offset = non-zero
4. dc = non-zero, offset = non-zero
Sketch your output plot




















Q1.7 What is the purpose of the command subplot ()? What do its argumentsrepresent?





6.3.4 Exponential sequence
Another basic discrete-time sequence is the exponential sequence. Such a
sequencecan be generated using the MATLAB operators .^ and exp.
Program 1.3a generates a real-valued exponential sequence
% Program 1.3a
% Generation of a real exponential sequence
clf;

71

n = 0:40;
a = +1.2;
K = 0.2;
x = K*a.^+n;
stem(n,x);
xlabel('Time index n');
ylabel('Amplitude');

To generate a complex-value exponential sequence, use program 1.3b.

% Program 1.3b
% Generation of a complex exponential sequence
clf;
phase = -0.1 + 1*i;
K = 2;
n = 0:80;
x = K*exp(phase*n);
subplot(2,2,2);
stem(n,real(x));
xlabel('Time index n');ylabel('Amplitude');
title('Real part');
axis ([0 60 -2.5 2.5])
subplot(2,2,4);
stem(n,imag(x));
xlabel('Time index n');ylabel('Amplitude');
title('Imaginary part');
axis ([0 60 -2.5 2.5])
subplot(2,2,[1 3]);
stem(n,abs(x));
xlabel('Time index n');ylabel('Amplitude');
title('Magnitude');
axis ([0 60 0 2.5])
Q1.8 Run Program 1.3a and generate the real-valued exponential sequence and
sketch it.





Q1.9 Which parameter controls the rate of growth or decay of this sequence?
Whichparameter controls the amplitude of this sequence?



Q1.10 What will happen if the parameter a is

72

1. less than 1 and greater than 0
2. less than 0 and greater than -1
3. less than -1
Modify the program and show all four graphs on a single screen. Show the output
withyour code to instructor.








Q1.11 Run Program 1.3b and generate the complex-valued exponential sequence and
sketch it.






Q1.12 What happens if the parameter c is changed to (1/12)+(pi/6)*i?



Q1.13 What are the purposes of the operators real() and imag()?




Q1.14 What is the difference between the arithmetic operators ^ and .^?





Q1.15 You can use the MATLAB command sum(s.*s) to compute the energy of a
realsequence s[n] stored as a vector s. Evaluate the energy of the real-valued
exponentialsequences x[n] generated in Questions Q1.8 and Q1.10. Give your
remarks on theenergies of all four signals.



73





6.3.5 Random sequence
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.
InMATLAB two types of (pseudo) random sequences are available. Therand(1,N) generates
a length N random sequence whose elements are uniformly distributed between [0,1]. The
randn(1,N) generates a lengthN Gaussian random sequence with mean 0 and variance 1.
Other random sequencescan be generated using transformations of the above functions. As
naturally occurring noise is random in nature (it may follow any statistical distribution
though) these commands are normally used to model noise in the MATLAB.
Q1.16 Write a MATLAB code to generate and display a random signal of length 100whose
elements are uniformly distributed in the interval [2, 2].



Q1.17 Write a MATLAB code to generate and display a Gaussian random signal of length 75
whose elements are normally distributed with mean 12 and a variance of 3.


Q1.18 Write a MATLAB program to generate and display four sample sequences of a
random sinusoidal signal of length 31
X[n] = A cos(n + ),
where the amplitude A and the phase are statistically independent random variables
withuniform probability distribution in the range 0 A 4 for the amplitude and in the range
0 2for the phase and sketch it down.










74

















6.4 SIMPLE OPERATIONS ON SEQUENCES
As indicated earlier, the purpose of digital signal processing is to generate a signal with
more desirable properties from one or more given discrete-time signals. The processing
algorithm consists of performing a combination of basic operations such as addition,
scalar multiplication, time-reversal, delaying, and product operation. We consider here a
couple of very simple examples to illustrate the application of such operations.
6.4.1 Signal addition
This is a sample-by-sample addition given by
{x
1
(n)+x
2
(n)}= {x
1
(n )}+{x
2
(n)}
It is implemented in MATLAB by the arithmetic operator +. However, the lengths of x1
(n) and 22 (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 augmentx1 (n) and 22 (n) so that they have the same position vector
n(and hence the same length). This requires careful attention to MATLABSindexing
operations. In particular, logical operation of intersection &, relational operations like <=
and ==, and the find function are required to make x
1
(n) and x
2
(n) of equal length. The
followingfunction, called the sigadd function, demonstrates these operations.
function [y,n] = sigadd(xl,nl,x2,n2)
% implements y(n) = xi(n)+x2(n)
% [y,n] = sigadd(x1,n1,x2,n2)
%y = sum sequence over n, which includes n1 and n2 initialization
% x1 = first sequence over nl
% x2 - second sequence over n2 (n2 can be different from nl)
n = min(min(n1) ,min(n2)) :max(max(n1) ,max(n2)) ; % duration of
y(n)
y1= zeros(1,length(n));
y2 = y1;
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 = yl+y2; % sequence addition

75

6.4.2 Signal multiplication
This is a sample-by-sample multiplication

{x
1
(n)x
2
(n)}= {x
1
(n )} . {x
2
(n)}

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

function [y,n] = sigmult(xl,nl,x2,n2)
% implements y(n) = xi(n)+x2(n)
% [y,n] = sigmult(x1,n1,x2,n2)
%y = sum sequence over n, which includes n1 and n2 initialization
% x1 = first sequence over nl
% x2 - second sequence over n2 (n2 can be different from nl)
n = min(min(n1) ,min(n2)) :max(max(n1) ,max(n2)) ; % duration of
y(n)
y1= zeros(1,length(n));
y2 = y1;
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 = yl.*y2; % sequence
multiplication
6.4.3 Signal smoothing
A common example of a digital signal processing application is the removal of the
noise component from a signal corrupted by additive noise. Let s[n] be the signal
corrupted bya random noise d[n] resulting in the noisy signal x[n] = s[n] + d[n]. Our
objective is to operate on x[n] to generate a signal y[n] which is a reasonable
approximation to s[n]. To this end, a simple approach is to generate an output
sample by averaging a number of input samples around the sample at instant n. For
example, a three-point moving average algorithm is given by
y[n] =1/ 3(x[n 1] + x[n] + x[n + 1])
% Program 1.4
% Signal Smoothing by Averaging
clf;
N = 60;
d = 0.8*(rand(1,N) - 0.5); % Generate random noise of length N
m = 1:N;
s = 2*m.*(0.9.^m); % Generate uncorrupted signal
x = s + d; % Generate noise corrupted signal
subplot(2,1,1);
plot(m,d,'r-',m,s,'g--',m,x,'b-.');
xlabel('Time index n');ylabel('Amplitude');
legend('d[n] ','s[n] ','x[n]');
x1 = [0 0 x];x2 = [0 x 0];x3 = [x 0 0];
y = (x1 + x2 + x3)/3;
subplot(2,1,2);
plot(m,y(2:N+1),'r-',m,s,'g--');

76

legend('y[n] ','s[n] ');
xlabel('Time index n');ylabel('Amplitude');
Q1.19Run Program 1.4 and generate all pertinent signals. show the output to your
instructor.
Q1.20 What is the form of the uncorrupted signal s[n]? What is the form of the
additive noise d[n]?




Q1.22In the second plot command, why the range of vector y is taken from 2:
N+1?Why didnt we plot it on its whole range?




Q1.23What is the purpose of the legend command?



77

Lab 7: Signals Transformation
7.1 Time Shifting
Consider a continues signal x(t). A time shifted version of this signal is
Y(t) = x(t t0)
Where to is a constant
Note that y(t0) = x(0) Hence if t0 is positive the shifted signal is delayed in time (shifted to
the right relative to x(t). If to is negative , y(t) is advanced in time (shifted to the left).
Matlab Implementation:
Inc=0.01;
t=-10:inc:10;
f=0.1;
t0=2;
x=sin(2*pi*f*t);
y=sin(2*pi*f*(t-t0));
hold on;
Plot(t,x);
Plot(t,y,r);
Grid on
Q1.1 Explain the above mention code.






Now for a discrete time signal each sample of x(n) is shifted by an amountk to obtain a
shifted sequence y(n).
y(n)= x(n- k)
If we letm = 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 nischanged by adding k to
each element. This is shown in the functionsigshift.
function [y,n]= sigshift(x,m,n0)
% implements y(n) = x(n-n0)
% [y,n]= sigshift(x,m,nO)
%
n = m+n0;
y = x;
7.2 Amplitude and Time Scaling
In amplitude scaling each sample is multiplied by a scalar a.
a {x(n)}= {ax(n)}
An arithmetic operator "*" is used to implement the scaling operation inMATLAB

78

For Time Scaling, Given a signal x(t) a time scaled version of this signal is
Y(t) = x(at) i
Where a is a real constant

Consider a = 2 such that y(t) = x(2t) i
For any particular value of time t = t0, y(t0) = x(2t0) and x(t0) = (yt0/2). It is seen that y(t0) =
x(2t0) is a time compressed (speed up) version of x(t0).

Consider a = such that y(t) = x(t/2)
For any particular value of time t = t0 y(t0) = x(t0/2) and x(t0) = y(2t0). It is observed that
y(t0) = x(t0/2) is a time (slowed down) version of x(t0)

Explanation
This coding plots the function x = sin(2ft) and also plots the function

Y(t) = x(2t);
Here a = 2 so the function y(t) will be compressed in time (speed up) version of the signal
x(t). Here the frequency will be doubled.

t=-10:0.01:10;
f=0.1;a=2;
x=sin(2*pi*f*t);
y=sin(2*pi*f*(a*t));
hold on
plot(x,t);
plot(y,t,r);
grid on

Q1.2 Explain the above mention code by taking a=0.5 and -0.5.







7.3 Folding or time reversal:
In this operation each sample of x(n) is flipped aroundn= 0 to obtain a folded sequence y(n).
y(n)= x(-n)
In MATLABthis operation is implemented by fliplr (x) function for sample values and by
-fliplr(n) function for sample positions as shown in thesigfold function.
function [y,n]= sigfold(x,n)
% implements y(n) = x(-n)
% [y,n]= sigfold(r,n)
%
y = fliplr(x); n = -fliplr(n);

79


Q1.3 Take a sinusoidal signal of frequency 1Hz and find out its time reversal and
plot these two signals.








Q1.4 Generate and plot each of the following sequences over the indicated interval.

























80



EXAMPLE: Generate the complex-valued signal
() =
(0.1+0.3)
, -10 < n < 10
and plot its magnitude, phase, the real part, and the imaginary part in four separate
subplots.
solution
MATLAB Script
>>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')


7.4 Even odd synthesis
A real-valued sequence x(n) is called even symmetric if
x(-n) = x(n)
Similarly, a real-valued sequence x(n) is called odd (antisymmetric) if
x(-n) = -x(n)
Then any arbitrary real-valued sequence z(n) can be decomposed into its even and odd
components
X(t) = Xe(t) + Xo (t) (2.2)
where the even and odd parts are given by
Xe(t) = [x(t) + x(-t)] and Xo(t) = [x(t) x(-t0] (2.3)

81

respectively. We will use this decomposition in studying properties of the Fourier transform.
Therefore it is a good exercise to develop a simpleMATLABfunction to decompose a given
sequence into its even and odd components. Using MATLAB operations discussed so far,
we can obtain the following evenodd function.
function [xe, xo, m] = evenodd(x,n)
% Real signal decomposition into even and odd parts x
if any(imag(x) ~= 0)
error('x is not a real sequence')
end
m = -fliplr(n) ;
m1 = min([m,n]); m2 = max([m,n]); m = m1:m2;
nm = n(1)-m(1); n1 = 1:length(n);
X1 = zeros(1,length(m));
X1(n1+nm) = x; x = X1;
xe = 0.5*(x + fliplr(x));
xo = 0.5*(x - fliplr(x))
The sequence and its support are supplied in x and n arrays, respectively. It first checks if
the given sequence is real and determines the support of the even and odd components in m
array. Itthen implements (2.3)with special attention to the MATLAB indexing operation.
Theresultingcomponents are stored in xe and xo arrays.

EXAMPLE Let s(n) = u(n) - u(n - 10). Decompose s(n) into even and odd components.
Solution
The sequence s(n), which is nonzero over 0<n<10, is called a rectangular pulse. We will use
MATLABto determine and plot its even and odd parts.
>>n = [0:10]; x = stepseq(0,0,10)-stepseq(10,0,l0);
>> [xe,xo,m] = evenodd(x,n);
>> figure(1);
>> subplot(2,2,1); stem(n,x); title(Rectaugu1ar pulse)
Q1.5 Plot the original sequence with there even odd combination in the same window and
sketch it down.











Example: Amplitude Modulation
An amplitude modulated signal can be generated by modulating a high-frequency
sinusoidal signal xH[n] = cos(Hn) with a low-frequency modulating signal
xL[n] =cos(Ln). The resulting signal y[n] is of the form
y[n] = A(1 + m. cos(wLn)) cos (wHn)

82

where m, called the modulation index , is a number chosen to ensure that (1 + m
xL[n])is positive for all n. Program 1.5 can be used to generate an amplitude
modulated signal.
% Program 1.5
% Generation of amplitude modulated sequence
clf;
n = 0:200;
m = 0.4;fH = 0.1; fL = 0.01;
xH = sin(2*pi*fH*n);
xL = sin(2*pi*fL*n);
y = (1+m*xL).*xH;
plot(n,y);grid;
xlabel('Time index n');ylabel('Amplitude');
Q1.6 Run the program 1.5 and provide its output.











7.4.1 Problems
1. Generate and plot the samples (use the stem function) of the following sequences
using MATLAB






2. Consider the following sequence.

Generate and plot the samples (use the stem function) of the following sequences.

83


3. Decompose the sequences given in Problem 1 into their even and odd
components. Plot these components using the stem function.
4. The operation of signal dilation (or decimation or down-sampling) is defined by

in which the sequence x(n) is down-sampled by an integer factor M. For example,
if

then the down-sampled sequences by a factor 2 are given by

a. Develop a MATLAB function dnsample that has the form
function y= dnsample(x,M)
to implement the above operation. Use the indexing mechanism of MATLAB
with careful attention to the origin of the time axis n = 0.
b. Generate x(n) = sin(0.125*pi*n), -50 <n < 50. Decimate x(n) by a factor of 4 to
generate y(n). Plot both x ( n) and y(n) using subplot and comment on the results.
c. Repeat the above using z(n) = sin(0.5m),50 <n < 50. Qualitatively discuss the
effectof down-sampling on signals.

84

Lab 8: Sampling, periodicity, Harmonics
and Sound Manipulation

8.1 PERIODICITY & HARMONICS
A very common class of signals that we encounter is the class of periodic signals. A
periodic continuous time signal has the property that there is a positive value of t
for which
X(t) = x(t + aT) A (continuous time)
Where a = 0,1,2,3,4
For all values of t. In other words a periodic signal has the property that it is
unchanged by a time shift of T. In this case we say that x(t) is periodic signal is the
sine signal.
X(t) = sin (wt) Where w = 2f; therefore
X(t) = sin (2ft)
Since sin(Q) = sin(Q + 2) therefore the signal is periodic with the period 2.
A periodic signal in discrete time is defined similarly to continuous time periodic
signal.
Specifically a discrete time signal x[n] is periodic with period N where N is
positive integer, i.e. if it is unchanged by a time shift of N i.e.
X[n] = x[n + bN] B (discrete time)
Where b = 0,1,2,3,4,
8.1.1 FUNDAMENTAL PERIOD
The fundamental period is the smallest positive value of T(continuous) or
N(discrete) for which the equations of periodicity held. Consider the example of a
sine function. In that case the signal is periodic on 2, 4, 6 and so on but the
fundamental time period of the signal is 2.
8.1.2 MATLAB EXPLANATION OF PERIODIC SIGNALS
Example # 1
t=0:0.01:6;
f=0.5;
x=sin(2*pi*f*t);
hold on;
plot(t,x);
xL=[1/f 1/f];
yL=[1 1];
plot(xL,yL.r:)
hold off
Note that in the above example
x (2) = x(2 + 2/0.01) = x(202)


85

8.1.3 HARMONICS:
Harmonics are integral multiples of a signal. Consider the signal
cos (w
o
t). its harmonics are cos(2 w
o
t), cos (3 w
o
t)is the fundamental harmonic.
8.1.4 EVEN, ODD HARMONICS:
If the harmonic of a signal function has an even co efficient it is called an even harmonic.
Otherwise if the co efficient is odd it is called an odd harmonic.
X(t) = Cos (w
o
t)
Cos (2 w
o
t), Cos (4 w
o
t) , Cos (6 w
o
t) .. Even Harmonics
Cos (3 w
o
t), Cos (5 w
o
t) , Cos (7 w
o
t) .. Odd Harmonics
Even, odd harmonic play an important role in signal construction. Different waveforms can
be obtained by adding one type of harmonic e.g adding infinite odd harmonics of
sine/cosine where generates a square wave. Both will have a 90 phase shift from each other.

Practically it is not possible to add all the (infinite) number of harmonics to obtain a perfect
square wave but as the number of harmonics is increased from 10 onwards we obtain a
decent square wave.
Example # 2
0.01;
0: : 4;
0.25;
2* * ;
fundamental=sin(w*t);
harmaonic2=sin(2*w*t);
harmaonic3=sin(3*w*t);
harmaonic4=sin(4*w*t);
hold on;
plot(t,fundamental,'ro');
plot(t,harmonic2,'k--');
plot(t,harmonic3,'m:'
inc
t inc
f
w pi f
=
=
=
=
);
plot(t,harmonic4,'y');
hold off


8.1.5 SQUARE WAVE GENERATION BY COS FUNCTIONS:
For square wave generation by cos functions odd harmonics we use.
X(t)=4/; (Cos (wt) 1/3 Cos (3 wt) + 1/5 Cos (5 wt)+.
Example#3
0: 0.01: 6
0.5
2* *
% function x(t)
t
f
w pi f
plot
=
=
=



86

8.2 SAMPLING, PLAYBACK & SOUND MANIPULATION
8.2.1 SAMPLING:
A continuous time signal x (t) has its value defined for every value of time t. on the other
hand a discrete time signal has its value at regular fired intervals. A continuous time signal
can be represented by its values or samples at points equally spaced in time.Consider a
continuous time signal x(t). This signal can be represented as a discrete time signal having
values of x(t)at n number of intervals spaced by a time interval Ts. We cant obtain all the
data in the signal by sampling it. Even if we sample at a very high rate some data will still be
lost but the results of course will be very good.
8.2.2 NYQUIST CRITERIA:
If the greater the number of samples the greater the accuracy, then why we dont sample at a
very high rate. There are two reasons for it. First of all high number of samples require a lot
of manipulation on the behalf of machine software that we are using which results in move
time. Secondly most of the vital data that we need can easily be obtained from low sampling
rates.
Therefore we need some criteria to define the rate at which the signals should be sampled.
This criterion is called the Nyquist criteria. According to it, the sampling frequency must (at
least) be twice the signal frequency. When the sampling rate doesnt satisfy the Nyquist.
When the sampling get the correct information about the signal. Reducing the number of
samples reduces information above original signal.
In MATLAB choosing a very high sampling rate simulates analog signals. Normally the
sampling frequency chooses to be 10 times higher than the maximum frequency component
in a given signal.
Example#01:
F=50;
Fs=10*50;
Ts=1/Fs;
T=1:Ts:0.1;
X=sin(2*pi*f*t);
stem(T,X)
EXPLANATION:
This example generates a sinusoidal signal x(t) = sin wt = sin 2ft will f = 50 Hz. The
sampling frequency fs is chosen to be 10 times the signal frequency. Note that in one
complete cycle it contains 10 samples.
Example#02:


87

f=1;
w=2*pi*f;
a=4;
fs1=2*f; fs2=10*f; fs3=20*f; fs4=40*f;
ts1=1/fs1; ts2=1/fs2; ts3=1/fs3; ts4=1/fs4;
t1=0:ts1:a; t2=0:ts2:a; t3=0:ts3:a; t4=0:ts4:a;
x1=cos(w*t1); x2=cos(w*t2);
x13cos(w*t3); x4=cos(w*t4);
subplot(221); stem(t1,x1);
subplot(222); stem(t2,x2);
subplot(223); stem(t3,x3);
subplot(224); stem(t4,x4);




EXPLANATION:
The above example samples a cos(wt) signal of frequency 1 Hz With the sampling
frequencies 2Hz, 10Hz, 20Hz & to Hz and displays the four sampled signals in &
independent plots using the stem command. We can easily see that as the closer and signal
accuracy increases.
Lab work
The purpose of this lab is to familiarize students with the concepts of sampling, quantization
and digitization to bits. Firstly a simple sine wave with high sampling frequency is
generated assuming it to be an analog signal. Secondly this assumed analog signal is
sampled. This sampled signal is then quantized to certain levels. After quantization bits are
assigned to each level.

Lab tasks:
Step 1:
Generate the sine wave with
- Frequency = 3Hz
- Sampling Frequency = 1000 Hz
- Amplitude = 1
- Number of cycles = 3
Note: Here the sine signal generated is assumed to be an analog signal.
Step 2:
Sample the assumed analog signal. To do so, write the code in following steps
- Generate a vector matrix having zeros; the length of this zero vector should be same
as that of assumed analog signal.
- Assign the value one 1 to every 40
th
sample in the zero vector. Now it is a pulse
train.
- Perform element by element multiplication between the assumed analog signal and
pulse train, to obtain the sampled signal.

88

Note: If plot of assumed analog signal and stem of sampled signal is in the same figure the
sampled values can be seen quite evidently from the figure, as shown below.

Step 3:
Quantize the sampled signals. To do so, write the code in following steps
- Remove zeros from the sampled signals. (Hint: Apply ~= , == or see help find).
- Assign levels to the sampled signal as shown in the figure below.
- Assign bits to the levels as according to the given table.

Amplitude level (A) Assigned value Assigned bits
A < -0.5 -2 0 0
-0.5 <A< 0 -1 0 1
0 <A< 0.5 1 1 0
A> 0.5 2 1 1

The quantization done based on levels defined is explained through the figure below.
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
-1
-0.5
0
0.5
1
1.5
Time
A
m
p
lit
u
d
e
Sampling of an Analog signal
Analog signal
Sampled values

89



8.2.3 SOUND MANIPULATION IN MATLAB
PLAYBACK An analog signal input to the sound card is sampled and digitized by sound
software, such as the sound recorder in windows. The recorded sound signal is saved in a
wav file. This file can be retrieved in MATLAB and played back.
Mono/Stereo Matlab Understands The Mono & Stereo Sounds As Single Column And 2
Column Vectors respectively. In STEREO different data using 2 hardware channels. STEREO
was different data for left and right speakers. Mono is represented by single column vector
and stereo by two column vectors in MATLAB.

8.2.4 MANIPULATION:
We know that MATLAB treats all the inputs and outputs as matrices/vector. Therefore for
the manipulation of an audio signal, is no different than altering the elements of a matrix.
Avoid using loops in manipulating a signal.


Example#03:
Make a folder in "c:" directory with name "soundlab" copy the file "testsound.wav" to the
"soundlab" folder.
[soundsig, fs, nbits]=wavread('c:\soundlab\testsound.wav');
left=soundsig(:,1);
right=soundig(:,2);
L=length(left);
half(left(1:2:L);
reverse=flipud(left);
wavplay(soundsig,fs);

EXPLANATION:

0 5 10 15 20 25 30 35 40
-2
-1.5
-1
-0.5
0
0.5
1
1.5
2
Samples
Quantized Signal
Sampled Signal

90

The wavread function reads the wav file and returns the sampled audio signal in
variable soundsig, fs is the sampling frequency & nbits represents the number of bits.
The wavplay function plays the audio signal with sampling frequency fs.

ECHO

Consider the following diagram input signal = sig.In echo generator the original signal is
attenuated, delayed and then added to the original signal. This is the signal that we hear and
experience an echo effect.



Example#04:
function[sigx, echosig, reflectedsig]=echobt031018(sig,fs,td,attn);
zer=zeros(td*fs,2);
sigx=[sig; zer];
refectedsig=[zer; sig*attn];
echosig=sigx+reflectedsig;

Example#05:
att=0.2;
td=1;
[signal,fs,nbits]=waveread(c:\soundlab\testsound.wav);
[signal,echo,ref]=echobt031018(signal,fs,td,att);
wavplay(signal,fs);
wavplay(echo,fs);
The coding in example # 5 produces a achosignal giving the reflected sound an
attenuation of 0.2 and time delay of 1 second. Next the warplay(signalx, fs plays the
original signal and wavplayecho,fs plays the echo version of the original signal with
sampling frequency fs.

Example # 6:
Replace the last line in example # 3 wavplay (soundsignal,fs) with the following values.
Run the example # 3 for each value given below.
1 wavplay(sound signal, fs);
2 wavplay (sound signal, 0.5* fs);
3 wavplay (sound signal, 2 *fs);
4 wavplay (half, fs);
5 wavplay (half, 0.5*fs);
6 wavplay (half, 2*fs);
7 wavplay ( reverse, fs);
8 wavplay (reverse, o.5*fs);
9 wavplay (reverse, 2*fs);
Turn on your speaker/headphones and hear the result for all above values numbered 1
through 9 by running the example # 3 & changing last line to the above values separately &
hearing the output.
Execute the following code and correctly answer the following question

91


Fs = 100; % Sampling frequency
Freq = 10; % Frequency of the signal
time = 0:1/Fs:(3/Freq); % Time vector
A = 4; % Amplitude of the signal
signal = A * sin(2*pi*Freq*time); % Signal it self
stem(time,signal)

Number of samples in the signal: _____________________
Number of cycles in the plotted signal: ______________
Number of samples in one cycle: ______________________
Time period of signal: _______________________________
Frequency of the signal: _____________________________

Power of the signal is defined by the equation

Power for a discrete time signal can be computed as

N is total number of discrete values in the signal.

Write the code to determine the power of the signal













Will the power of the signal going to change if Fs (sampling frequency) of the signal is
increased in this case.
a. Yes b. No

SQUARE Square wave generation.
SQUARE(T) generates a square wave with period 2*Pi for the elements of time vector T.
SQUARE (T) is like SIN(T), only it creates a square wave with peaks of +1 to -1 instead of a
sine wave.
For example, generate a 30 Hz square wave:
t = 0:.0001:.0625;

92

y = SQUARE(2*pi*30*t);, plot(t,y)

SAWTOOTH Sawtooth and triangle wave generation.
SAWTOOTH(T) generates a sawtooth wave with period 2*pi for the elements of time vector
T. SAWTOOTH(T) is like SIN(T), only it creates a sawtooth wave with peaks of +1 to -1
instead of a sine wave.

SINC Sin(pi*x)/(pi*x) function.
SINC(X) returns a matrix whose elements are the sinc of the elements of X, i.e.
y = sin(pi*x)/(pi*x) if x ~= 0
= 1 if x == 0
where x is an element of the input matrix and y is the resultant output element.
With the execution of the code

Fs = 1000;
freq = 10;
time = -(2/freq) : 1/Fs : (2/freq);
plot(time,sinc(2*pi*freq*time))

sinc function is generated and the output looks like

Generate the square wave with
- Frequency = 10Hz
- Sampling Frequency = 30 Hz
- Amplitude = 10
- Number of cycles = 4

Generate the sawtooth wave
- Frequency = 1 Hz
- Sampling Frequency = 10 Hz
- Amplitude = 1
- Number of cycles = 10
- DC shift = 2

Generate a full wave rectified waveform of the sine wave
-0.2 -0.15 -0.1 -0.05 0 0.05 0.1 0.15 0.2
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
1.2
Sinc function

93

Hint: use the element by element multiplication of sine and square waves having the same
frequencies.


8.2.5 EXERCISE:

E.1. Write MATLAB function for plotting the 5 harmonics of a signal x(t)=cos(wt) with a
fundamental frequency of f = 0.5 Hz. Take t = 0:0.01:2

E.2. What are the frequencies and Time periods at the all 5 harmonics in questions E.1.

E.3. Consider the general form of an equation
F(t) = 4/n sin(nwt) 1 n

Take the case of 1 n 5, w = 2f, f=2Hz
t = -2:0.01: 2. Plot all the 5 harmonics of the above function in same figure using the subplot
command. Subplot (511), subplot(512) --------
Subplot (513), Subplot(514), Subplot (515),

E.4. If the frequency of x(t) = sin(2ft) is f = o.2hz what will be the time period of the 4rth
harmonic of the above signal x(t). plot x(t) and its 4rth harmonic and check the time period
of 4rth harmonic in MATLAB. Do result agree with your theoretical calculation of time
period of 4rth harmonic?

E.5. Refer to general function f(t) in question 3 Now
inf
1
(4/( 8 ))*sin( * * )
n
n pi n w t
=


Plot the function f(t) in Matlab upto n=5 take f=1Hz, t=0:0.01:4

E.6. Implement example # 4 example # 5. Run the example # 5 for the following values of
att and td and explain what is the difference between the following. Speakers
/Headphones should be on to hear the output.

1) att =0.5 2) att =0.5 3) att =0.3 4) att=0.1
td=.5 td=1 td=1.3 td=2

E.7. Do the example # 6 and hear the output for all the values numbered 1 to 9. Give
explanation for each from 1 to 9 that what we hear? 3 what is the effect of 0.5fs and 2fs?

E.8. Consider a signal y(t) = sin(wt) where w=2f Take the case when
f = 23 (Hertz). What should be the sampling frequency (fs) according to Nyquist Criteria?

E.9. If we use fs = 460 (sampling frequency) in above question then does it satisfy the
Nyquist Criteria?
For fs = 460 how many samples are there in each cycle of sin(wt).

94


E.10. Consider a signal s(t) = 50 cos (20t) + 10 cos (100t) what is the maximum frequency
component in the above signal (Remember the relation cos wt = cos 2ft)
Fmax = Hz
What should be the sampling frequency according to the Nyquist Criteria in the above
signal s(t)?

E.11. Refer to the echo block diagram given at back of page # 2. we want to modify &
implement a new echo generator with its block diagram below. Modify the codes of example
# 4 and example # 5 so that it implements, the system given below




Where = attenuation
& td = Time Delay









2 td
+
2
Input Sig
Reflected Sig
Output Sig

95

Lab 9: Convolution and LTI Systems
Students often have a difficult time understanding what convolution is. Students
canoften evaluate the convolution integral (continuous time case), convolution sum
(discrete-time case), or perform graphical convolution but may not have a good
grasp of what is happening. In other words, students can solve the formula but often
do not understand the result or why they get that result. Most engineering texts
explain convolution by giving the convolution integral (and/or convolution sum)
and doing some mathematical and graphical examples. They often do not attempt to
explain how convolution corresponds with what is happening between the system
and the input to give the output response. In this paper, a more intuitive explanation
of convolution is given and MATLAB and SIMULINK simulations of physical
systems are used to give a more intuitive approach to understanding convolution
from a systems perspective.
9.1 Introduction
Students are often introduced to convolution before they see the use for it. In most
Electrical Engineering curriculums, convolution is introduced in sophomore or
junior level signals and systems courses. Convolution is often performed
numerically and students have a tendency to blindly accept the results their
calculator or computer provides. Thus it is important for students to understand the
use, along with the theory of convolution, so they can better evaluate the results they
get from convolution. If convolution is explained from a systems perspective with
good examples, they will see the use, and hopefully understand the theory and be
able to determine if their results make sense. This lab proposes explaining
convolution from a systems perspective using simulations of familiar systems. It is
hoped that this will give students insight into what is happening with convolution.
9.2 System
A system is a plant or a process that produces a response called an output in response
to an excitation called an input.

If a systems input and output signals are scalars, the system is called a single-input
single-output (SISO) system. If a systems input and output signals are vectors, the

96

system is called a multiple-input multiple-output (MIMO) system. Asingle-input
multiple-output (SIMO) system and a multiple-input single-output (MISO) system can
also be defined in a similar way.
For example, a spring-damper-mass system is a mechanical system whose output to
an input force is the displacement and velocity of the mass. Another example is an
electric circuit whose inputs are voltage/current sources and whose outputs are
voltages/currents/charges in the circuit. A mathematical operation or a computer
program transforming input argument(s) (together with the initial conditions) into
output argument(s) as a model of a plantor a process may also be called a system. A
system is called a continuous-time/discrete-time system if its input and output
arebothcontinuous-time/discrete-time signals.
9.2.1 DISCRETE SYSTEMS
Mathematically, a discrete time system (or discrete system for short) is describedas
an operator T[.] that takes a sequence x(n) (called excitation)and transforms it into
another sequence y(n) (called response). That is,
y[n]=T[x[n]]
we will say that the system processes an input signal into an output signal. Discrete
systems are broadly classified into linear and nonlinear systems. We will deal mostly
with linear systems.
9.2.1.1 LINEARSYSTEMS
A system is said to be linear if the superposition principle holds in the sense that it satisfies
the following properties:
- Additivity:The output of the system excited by more than one independent
input is the algebraic sum of its outputs to each of the inputs applied
individually.
- Homogeneity: The output of the system to a single independent input is
proportional to the input.
This superposition principle can be expressed as follows:


97

9.2.1.2 Linear time-invariant (LTI) system
A linear system in which an input-output pair, x(n) and y(n), is invariant to a shift n
in time is called a linear time invariant system. For an LTI system the linear system
L[.] and the shifting operators are reversible as shown below.

9.2.1.3 Stability
This is a very important concept in linear system theory. The primary reason for
considering stability is to avoid building harmful systems or to avoid burnout or
saturation in the system operation. A system is said to be bounded-input bounded-
output (BIBO) stable if every bounded input produces a bounded output.

An LTI system is BIBO stable if and only if its impulse response is
absolutelysummable.
9.2.1.4 Causality
This important concept is necessary to make sure that systemscan be built. A system
is said to be causal if the output at index nodepends only on the input up to and
including the index no; that is, theoutput does not depend on the future values of the
input. An LTI systemis causal if and only if the impulse response
h(n) =o, n < O (2.13)
Such a sequence is termed a causal sequence. In signal processing, unlessotherwise
stated, we will always assume that the system is causal.
9.3 Convolution Definition and Systems Background
We begin with the definition of convolution and a brief discussion of some system
theory.
9.3.1 Definition of Convolution
Convolution is usually defined via the convolution integral for continuous time
functions or the convolution sum for discrete-time functions. The convolution of two
continuous time functions h(t ) and x(t ) writtenh(t )* x(t ) and is given by the
convolution integral

The convolution integral exists if h(t ) and x(t ) are absolutely integrable.
The convolution of two discrete-time functions h[n] and x[n] written h[n]* x[n]can be
found using the convolution sum

98


Note that convolution is both commutative and distributive.
9.3.2 Matlab Implementation
In general , the convolution operation is used to describe the response of an LTI system. In
DSP it is an important operation and has many other uses.
Exercise 1
Convolve the following by hand

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









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

Exercise 2
Log on to Matlab and enter:

x1 =[2.4 3.6 0.2 5.3 1.4 4.4 3.6];
x2=[3.1 3.8 5.2 7.7 2.5 4.6];
y=conv(x1,x2)

Write down the output





99







You will note that there are no marker arrows in this sequence, which mean that the
sequences start from x = 0.
However if the sequences do not start at x = 0 then the problem is a little more complicated.
Consider the following sequence:

x1[n] * x2[n] where:

x1[n]={2.4 3.6 0.2 5.3 1.4 4.4 3.6}

x2[n]={3.1 3.8 5.2 7.7 2.5 4.6}

Note the * in this context means convolve with

As these are different lengths and the starting points are not the first number they need to be
padded with zeros as shown below

0 0 2.4 3.6 0.2 5.3 1.4 4.4 3.6
3.1 3.8 5.2 7.7 2.5 4.6 0 0 0

To solve this we need to pad these values out with zeros to make them all the same length.
This can be solved by writing a MATLAB function.
However, the conv function neither provides nor accepts any timing information if the
sequences have arbitrary support. To solve this inconvenience, a simple extension of the
conv function, called conv_m, which performs the convolution of arbitrary support
sequences can now be designed as

function [y, ny] = conv_m(x, nx, h, nh)
% Modified convolution routine for signal processing
% --------------------------------------------------------------
% [y, ny] = convolution result
% [x, nx] = first signal
% [h, nh] = second signal
%
nyb = nx(1) + nh(1);
nye = nx(length(x)) + nh(length(h));
ny = [nyb:nye];
y = conv(x, h);
% End of the function
Exercise 3
Copy the MATLAB program from the handout and then using this function, plot the
sequences for

100


x1[n] = {0, 0, .8, .8, .8, .8, .8, .8, }
x2[n] = { 0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.7}

and their convolution sum

x1=[.8 .8 .8 .8 .8 .8];n1=(2:7);
x2=[.7 .7 .7 .7 .7 .7 .7 .7 .7 ];n2=(-4:4);
convstem(x1,n1,x2,n2)

9.3.3 Correlation of sequences
Correlation is an operation used in many applications in digital signal processing. It is a
measure of the degree to which two sequences are similar. Given two real-valued sequences
x(n) and y(n) of finite energy, the crosscorrelation of x(n) and y(n) is a sequence ) (l r
xy

defined as
( ) ( ) ( )
xy
n
r l x n y n l

=
=


The index l is called the shift or lag parameter. The special case when ( ) ( ) y n x n = is called
autocorrelation and is defined by
( ) ( ) ( )
xx
n
r l x n x n l

=
=


If we compare the convolution operation with the crosscorrelation of two sequences, we
observe a close resemblance. The crosscorrelation ( )
xy
r l can be put in the form
( ) ( ) ( )
xy
r l x l y l = -

with the autocorrelation ) (l r
xx
in the form
( ) ( ) ( )
xx
r l x l x l = -

Therefore these correlations can be computed using the conv function if sequences are of
finite duration.
The signal-processing toolbox MATLAB provides a function called xcorr for sequence
correlation computations. However, the function does not provide the timing (or lag)
information, which then must be obtained by some other means.

A. Convolution of Sequences
Given the following two sequences

x
1
(n) = [ 0, 0, 1, 1, 1, 1, 1] and x
2
(n) =[0, 0, 0, 1, 1, 1]
| |

101

1. For 10 s k s 10, plot x
1
(k) and x
2
(k) using the stem function.








2. Plot x
1
(k) and x
2
(-k) and then with a loop control structure, write a program to determine
y(0) =
10
1 2
10
( ) ( )
k
x k x k
=











3. Plot x
1
(k) and x
2
(1-k) and then, with a loop control structure, write a program to
determine
y(1) =
10
1 2
10
( ) (1 )
k
x k x k
=











4. Plot x
1
(k) and x
2
(-1-k) and then with a loop control structure, write a program to
determine
y(-1) =
10
1 2
10
( ) ( 1 )
k
x k x k
=










102





5. Develop a program to determine
1 2 1 2
( ) ( )* ( ) ( ) ( ) 15 15
k
y n x n x n x k x n k n

=
= = s s


6. For 15 s n s 15, plot the sequence y(n) obtained in (5). What are the beginning point and
end point of y(n) that are non-zero values?








7. Invoke the following MATLAB commands and plot the result (y versus ny)
>> x1 = [0, 0, 1, 1, 1, 1, 1]; nx1 = [-3:3];
>> x2 = [0, 0, 0, 1, 1, 1]; nx2 = [-3:2];
>> [y, ny] = conv_m(x1, nx1, x2, nx2);
8. Compare the plot in (7) to the plot in (6). Briefly explain what you get.











B. Correlation of Sequences
1. Create a MATLAB function called xcorr_m to perform the correlation operation based
on the convolution operation.
2. Let x(n) = [3, 11, 7, 0, -1, 4, 2] be a prototype sequence and y(n) = x(n-2)+w(n) be its
noise-corrupted |
and shifted version. Write the following code and save as a M-file.

% noise sequence 1
x =[3, 11, 7, 0, -1, 4, 2]; nx = [-3:3]; % given signal x(n)
[y, ny] = sigshift(x, nx, 2); % obtain x(n-2)
w = randn(1, length(y)); nw= ny; % generate w(n)
[y, ny] = sigadd(y, ny, w, nw); % obtain y(n) = x(n-2) + w(n)
[rxy, nrxy] = xcorr_m(x, nx, y, ny); % crosscorrelation
subplot(2, 1, 1); stem(nrxy, rxy);
axis([-5, 10, -50, 250]); xlabel(lag variable l);
ylabel(rxy); title(Crosscorrelation: noise sequence 1);

103

%
% noise sequence 2
x =[3, 11, 7, 0, -1, 4, 2]; nx = [-3:3]; % given signal x(n)
[y, ny] = sigshift(x, nx, 2); % obtain x(n-2)
w = randn(1, length(y)); nw = ny; % generate w(n)
[y, ny] = sigadd(y, ny, w, nw); % obtain y(n) = x(n-2) + w(n)
[rxy, nrxy] = xcorr_m(x, nx, y, ny); % crosscorrelation
subplot(2, 1, 2); stem(nrxy, rxy);
axis([-5, 10, -50, 250]); xlabel(lag variable l);
ylabel(rxy); title(Crosscorrelation: noise sequence 2);

3. Run the script saved in (2) and Sketch the output figure.










104

Lab 10: Laplace-Transform
10.1 Laplace Transform
Laplace transform of a function f(t) is defined as

Where
Laplace transform of a function f(t) can be obtained with Matlab's function Laplace.
Syntax: L =laplace(f)
The usage is demonstrated in the following examples.
a) x(t) = t, you can use the following MATLAB program.

>> syms f t
>> f=t;
>> laplace(f)

ans =1/s^2
where f and t are the symbolic variables, f the function, t the time variable.

b)

>> syms t s
>> f=-1.25+3.5*t*exp(-2*t)+1.25*exp(-2*t);
>> F=laplace(f,t,s)
>>simplify(F)
>>pretty(ans)

Alternatively, one can write the function f(t) directly as part of the laplace command:
>>F2=laplace(-1.25+3.5*t*exp(-2*t)+1.25*exp(-2*t))

C)
Matlab performs Laplace transform symbolically. Thus, you need to first define the variable
t as a "symbol".
>> syms t
Next, enter the function f(t):
>> f=5*exp(-2*t);
Finally, enter the following command:
>> L=laplace(f)
Matlab yields the following answer:

105

L =

5/(s+2)
You may want to carry out the transformation by hand (or using Laplace transform table) to
verify this result.
10.1.1 Inverse Laplace Transform with MATLAB:

The command one uses now is ilaplace. One also needs to define the symbols t and s.
Lets calculate the inverse of the previous function F(s),
1)

>> syms t s
>> F=(s-5)/(s*(s+2)^2);
>> ilaplace(F)
ans =
-5/4+(7/2*t+5/4)*exp(-2*t)

>> simplify(ans)

ans =
-5/4+7/2*t*exp(-2*t)+5/4*exp(-2*t)

>> pretty(ans)
- 5/4 + 7/2 t exp(-2 t) + 5/4 exp(-2 t)
Which corresponds to f(t)

Alternatively one can write
>> ilaplace ((s-5)/(s*(s+2)^2))
2)
>> F=10*(s+2)/(s*(s^2+4*s+5));
>> ilaplace(F)
ans =
-4*exp(-2*t)*cos(t)+2*exp(-2*t)*sin(t)+4
Which gives f(t),

3)
>> syms F S
>> F=24/(s*(s+8));

106

>> ilaplace(F)
ans =
3-3*exp(-8*t)

4) Find the inverse Laplace transform of

In Matlab Command window:
>> ilaplace(1/s-2/(s+4)+1/(s+5))
Matlab result:
ans =

1-2*exp(-4*t)+exp(-5*t)
or

which is the solution of the differential equation
10.1.2 Zeros and poles
To find the zero, poles and gain of a transfer function from the vectors num and den
which contain the co efficients of the numerator and denominator polynomials type.
[z,p,k]= tf2zp(num,den)
The zeros are stored in z, poles are stored in p and the gain is stored in k. To find the
numerator and denominator polynomials from z, p and k type.
(num,den) =zp2tf [z,p,k]
10.1.3 Frequency response
To compute the frequency response it (w) of a transfer function, store the numeratror and
denominator of the transfer function in the vectors numand den define a vector w that
contains the frequencies for which H(w) is to be computed for exampleW = a:b:c where a is
the lowest frequency c is the highest frequency and b is the increment n frequency.
The command is = freqs (num, den, w)
Returns a complex vector H that contains the value of H(w) for each frequency in w. To
draw a bode plot of a transfer function which has been stored in the vectors num and den
type bode (num, den).
If denominator >= Numerator than the polynomial is not in a proper form. To convert an
improper polynomial to a proper one we require long division. After long division and the
partial fraction expansion we can get the required inverse Laplace Transformation.
The command used to covert an improper H to proper H is
[Q,R]=deconv(B,A)
This deconvolves vector A out of vector B. The result is returned in vector Q and the
remainder in vector R such that
B= conv (A,Q) + R

107

If A and B are vectors of polynomial coefficients deconvolutions is equivalent to division.
The result of dividing B/A is Quotient Q and the remainder R.
The command
[R,P,k] =residues (B,A)

Returns the residues in column vector R, poles in column vector P and direct terms in row
vector K. K vector is empty if length (B) < length (A) I;e if H is in the proper form.

Example
=
5

2
4 + 3

In this case the num = [1 -5] den = [1 -4 3]
[r, p, k] = residue (den,num)

Example # 2 gives r = [-1 2], p= [3 1], k=[ ]

The general expression is given below
B(S) = K(S) + R(1) + R(2) + . + R(n) --------------------- (A1)
A(S) S-P(1) S-P(2) S-(n)

Putting values of r, p and k in eq A1, we have
B(S) = 0 + -1 + 2 ----------------------- (B1)
A(S) S-3 S-1

Therefore Matlab makes the task of creating partial fractions much easier.

10.1.4 Lab Task:
Use laplace to find the Laplace transforms

Use ilaplace to find the Inverse Laplace transforms



108

Lab 11: Z-transform and Inverse Z-
transform Analysis
11.1 Description:
In mathematics and signal processing, the Z-transform converts a discrete time-domain
signal, which is a sequence of real or complex numbers, into a complex frequency-domain
representation.
The Z-transform, like many other integral transforms, can be defined as either a one-sided or
two-sided transform.
11.1.1 Bilateral Z-transform
The bilateral or two-sided Z-transform of a discrete-time signal x[n] is the function X(z)
defined as

11.1.2 Unilateral Z-transform
Alternatively, in cases where x[n] is defined only for n 0, the single-sided or unilateral Z-
transform is defined as

In signal processing, this definition is used when the signal is causal. As analog filters are
designed using the Laplace transform, recursive digital filters are developed with a parallel technique
called the z-transform. The overall strategy of these two transforms is the same: probe the impulse
response with sinusoids and exponentials to find the system's poles and zeros. The Laplace transforms
deals with differential equations, the s-domain, and the s-plane. Correspondingly, the z-transform
deals with difference equations, the z-domain, and the z-plane. However, the two techniques are nota
mirror image of each other; the s-plane is arranged in a rectangular coordinate system, while the z-
plane uses a polar format. Recursive digital filters are often designed by starting with one of the
classic analog filters, such as the Butterworth, Chebyshev, or elliptic. A series of mathematical
conversions are then used to obtain the desired digital filter. The Z transform of a discrete time system
X[n] is defined as Power Series.

11.1.2.1 Rational Z-transform to factored Z-transform:
Example:
Let the given transfer function be in the rational form,
2z
4
+16z
3
+44z
2
+56z+32
G(z)= --------------------------------
3z
4
+3z
3
-15z
2
+18z-12

109

It is required to convert it into factored form, so that we can find the poles and zeros
mathematically by applying quadratic equation.
Matlab command required for converting rational form to factored form be
Zp2sos
The factored form of G(z) as evaluated by zp2sos be,

G(z)=( 0.6667 + 0.4z
-1
+ 0.5333 z
-2
) (1.000 + 2.000 z
-1
+2.000 z
-2
)
(1.000 + 2.000z
-1
-4.000z
-2
)(1.000 - 1.000 z
-1
+ 1.000 z
-2
)

11.1.2.2 Factored Z-transform / zeros,poles to rational Z-transform:

It is the inverse of the above case, when the transfer function is given in factored form and it
is required to convert in rational form then a single matlab command can serve the
purpose.
Example:
Lets use the above result i-e;transfer function in factored for,

G(z)= ( 0.6667 + 0.4z
-1
+ 0.5333 z
-2
) (1.000 + 2.000 z
-1
+2.000 z
-2
)
(1.000 + 2.000z
-1
-4.000z
-2
)(1.000 - 1.000 z
-1
+ 1.000 z
-2
)

For building up transfer function in rational form we find the poles and zeros of above
system simply by using Matlab root command or by hand. Or simply we have poles and
zeros of the given system we can find the transfer function in factored form.

Matlab command that converts poles and zeros of the system in to transfer function is
zp2tf .

11.1.2.3 Rational Z-transform to partial fraction form:

This technique is usually used, while taking the inverse Z-transform and
when the order H(z) is high so that it is quite difficult to solve it mathematically.
Example:
Consider the transfer function in the rational form i-e;
18z
3
G(z)= ------------------
18z
3
+3z
2
-4z-1
We can evaluate the partial fraction form of the above system using matlab command. The
partial fraction form be,
G(z)= 0.36__ + __0.24__ + _0.4____
1 0.5z
-1
1+0.33 z
-1
(1+0.33 z
-1
)

Matlab command that converts rational z-transform in to partial fraction form is
residuez.


110

11.1.2.4 Partial fraction form to Z-transform:
This technique is used when it is required to convert partial fraction expression in to rational
Z-transform.
Example:

Take the partial fraction form of above ,
The partial fraction form be,
G(z)= 0.36__ + __0.24__ + _0.4____
1 0.5z
-1
1+0.33 z
-1
(1+0.33 z
-1
)
Matlab command that converts partial fraction form into rational z-transform isresiduez
Zplane:
Zero-pole plot
zplane(b,a)
This function displays the poles and zeros of discrete-time systems.
MATLAB:
syms z n
a=ztrans(1/16^n)
11.2 Inverse Z-Transform:
MATLAB:
syms Z n
iztrans(3*Z/(Z+1))
11.3 FUNCTIONS RELATED TO Z-TRANSFORM
Following are the MATLAB commands which are related to the Z transform
1- freqz used for calculating / displaying frequency response
2- impz used for calculating / displaying impulse response
3- z place plots the zeros and poles with unit circle
4- tf2zp finds zeros, poles and gain from H = B/A
5- ZP2tf Transforms from zero, poles , gain back to t = B/A
6- Residuez Finds residues, poles, direct terms of partial fraction
7- Poly convert roots to polynomial
8- Roots computes roots of a polynomial
9- conv used for multiplying 2 polynomials A & B.
11.3.1 Pole Zero Diagrams For A Function In Z Domain:
Z plane command computes and display the pole-zero diagram of Z function.The Command is
Zplane(b,a)
To display the pole value, use root(a)
To display the zero value, use root(b)


Matlab Code:

b=[0 1 1 ]
a= [1 -2 +3]
roots(a)
roots(b)

111

zplane(b,a);

ans =
1.0000 + 1.4142i
1.0000 - 1.4142i

ans=
-1


Frequency Response:
The Freqz function computes and display the frequency response of given Z- Transformof the
function
freqz(b,a,Fs)
b= Coeff. Of Numerator
a= Coeff. Of Denominator
Fs= Sampling Frequency
Matlab Code:
b=[2 5 9 5 3]
a= [5 45 2 1 1]
freqz(b,a);











112







Example:

Plot the magnitude and phase of the frequency response of the given digital filter Using freqz
function:
Y(n) = 0.2x(n) + 0.52y(n-1) 0.68(y(n-2)

Matlab Code:
b = [0.2];
a= [1, -0.52, 0.68];
w = [0:1:500]*pi/500;
H=freqz(b,a,w);
magH = abs(H);
phaH = angle(H)*180/pi;
subplot(2,1,1);
plot(w/pi,magH);
title('Magnitude Response');
xlabel('frequency in pi units');
ylabel('H');
subplot(2,1,2);
plot(w/pi,phaH);
title('Phase Response');
xlabel('frequency in pi units');
ylabel('Degrees');


LAB TASK:


113

Task#1: Express the following z-transform in factored form , plot its poles and zeros, and
then determine its ROCs.
2z
4
+16z
3
+44z
2
+56z+32
G(z)= --------------------------------
3z
4
+3z
3
-15z
2
+18z-12
Task#2:Determine the partial fraction expansion of the z-transform G(z) given by

18z
3
G(z)= ------------------
18z
3
+3z
2
-4z-1

Task#2: Evaluate the z-transform of the following
a) n
b) n
2

c) a
n

d) n
2
a
n

e) sin(bn)
f) cos(bn)
g) a
n
sin(bn)
h) a
n
cos(bn)




114

Lab 12: Fourier series and the Gibbs
Phenomenon
12.1 The Fourier series of the Square Wave
Let the function sq(t) be defined by

The Fourier series associated with this function is

The Fourier coefficients of this 1-periodic function are given by

Because sq(t) is odd, it is clear that bk = 0 for all k0. From symmetry itis clear that:

Thus, we find that the Fourier series associated with sq(t) is

We would now like to examine the extent to which this series truly represents the square
wave.
12.2 A Quick Check
Before proceeding to analyze the series we have found, it behooves us to check that the
calculations were performed correctly. For a 1-periodic function like sq(t), Parseval's
equation states that


In our case this means that

115


We can check that this sum is correct using MATLAB. One way to perform a quick check is
to give MATLAB the commands
L = [1:2:10001];
(8/pi^2) * sum(1./L.^2)
MATLAB responds with
ans =
1.0000
which is an indication that we may have performed all of the calculationscorrectly.A second
way to have MATLAB check this computation is to give MATLAB the commands
syms k
(sym('8')/sym('pi')^2) * symsum(1/(2*k+1)^2,k,0,Inf)
MATLAB responds to these commands with
ans =
1
indicating that the series does, indeed, sum to 1.

Figure 5.1: Summing the Fourier series. The ringing" associated with Gibb'sphenomenon is
clearly visible.
12.3 Seeing" the Sum
It is not difficult to have MATLAB calculate the Fourier series and displayits values.
Conisder the following code:
t = [-500:500] * 0.001;
total = zeros(size(t));
for k = 1 : 2 : 101
total = total + (4/pi) * sin(2*pi*k*t) / k;
end

116

plot(t,total)
This code defines a time" vector, t, with 1001 elements. It then defines avector to hold the
sum, total, and proceeds to sum the first 51 terms inthe Fourier series. The code causes
MATLAB to produce the plot shown inFigure 5.1. The ringing" produced by Gibb's
phenomenon is clearly visible.
12.4 The Experiment
Letsaw(t) = tfor -1/2 < t< 1/2 and continue saw(t) periodically outside of this region.
1. Calculate the Fourier coefficients associated with saw(t).
2. Check Parseval's equation for saw(t) both numerically and symbolically.
3. Sum the first 3 terms in the Fourier series and plot the Fourier seriesas a function
of time.
4. Sum the first 10 terms in the Fourier series and plot the Fourier seriesas a function
of time.
5. Sum the first 50 terms in the Fourier series and plot the Fourier seriesas a function
of time.
When summing the Fourier series, make sure that the time samples you take are sufficiently
closely spaced that you clearly see Gibb's phenomenon.
Example # 1 (MATLAB IMPLEMENTATION)
Squarewavefourierseries.m
function [t, fourierseries]= squarwavefourierseries(har,tmax);
fo= 1/(2*pi);
wo= 2*pi*fo;
t=-tmax : 0.05 : tmax;
n=1: har;
ao=1/2;
an=(2./(n*pi)).* sin(n*pi/2);
bn= zeros (1, length(n));
y= zeros (har,length(t));
for n=1:har
y(n,:) = an(n) * cos( n* wo*t) + bn (n) * sin(n*wo*t);
end
fourierseries = ao + sum (y,1)

Save this function with the some name i:e squarewavefourierseries. This function takes the
harmonics in variable har. These are the number of harmonics to be computed in the
fourier series expansion. The variable tmax contains the maximum time limit of the signal.
The function returned fourierseries variable which contains fourier series expansion and
t contains the time.

Example # 2:
Close All;
tmax= 2*Pi;
[tx1,fx1] =squarewavefourierseries(2000, tmax);
Figure;
Plot(tx1,fx1); grid;
[tx2,fx2] =squarewavefourierseries(50, tmax);
Figure;

117

Plot(tx2,fx2); grid;
[tx3,fx3] =squarewavefourierseries(20, tmax);
Figure;
Plot(tx3,fx3); grid;
[tx4,fx4] =squarewavefourierseries(10, tmax);
Figure;
Plot(tx4,fx4); grid;
[tx5,fx5] =squarewavefourierseries(3, tmax);
Figure;
Plot(tx5,fx5); grid;
[tx6,fx6] =squarewavefourierseries(1, tmax);
Figure;
Plot(tx6,fx6); grid;
This coding calls the function squarewavefourierseries with different values for har
variable and plots the fourier series representation for each. Note that as har values
increases the waveform becomes more closer to the ideal one.
Example # 3:
function[t, fourierseries]= sawtoothfourierseries(har,tmax);
a=5;
fo=1/(2*pi);
wo= 2*pi*fo;
t= -tmax : 0.05 : tmax;
n=1: har;
ao=0;
an= zeros(1,length(n));
bn=(2*a)./(n.*n.*pi.*pi).*(sin(n*pi)-(n*pi).*cos(n*pi));
y=zeros(har,length(t));
for n=1:har
y(n,:)= an(n) * cos(n* wo*t)+ bn(n) * sin( n*wo*t);
end
fourierseries= ao+ sum(y,1);
Save this function with the some name i:e sawtoothfourierseries. This function takes the
harmonics in variable har and the max time limit in variable tmax. These are the number
of harmonics to be computed in the Fourier series expansion. The variable tmax contains
the maximum time limit of the signal. The function returned fourierseries variable which
contains Fourier series representation for the sawtooth waveform. The t variable is the axis
for that signal. As n approaches to infinity, the waveform approaches to an ideal wave
form of sawtooth.
Example # 4:
Close All;
tmax= 2*Pi;
[tx1,fx1] = sawtoothfourierseries (2000, tmax);
Figure;
Plot(tx1,fx1); grid;
[tx2,fx2] = sawtoothfourierseries (50, tmax);
Figure;
Plot(tx2,fx2); grid;
[tx3,fx3] = sawtoothfourierseries (20, tmax);
Figure;

118

Plot(tx3,fx3); grid;
[tx4,fx4] = sawtoothfourierseries (10, tmax);
Figure;
Plot(tx4,fx4); grid;
[tx5,fx5] = sawtoothfourierseries (3, tmax);
Figure;
Plot(tx5,fx5); grid;
[tx6,fx6] = sawtoothfourierseries (1, tmax);
Figure;
Plot(tx6,fx6); grid;

This coding calls the function squarewavefourierseries with different values for har
variable and plots the Fourier series representation for each. Note that as har values
increases the waveform becomes closer to the ideal one.

119

Lab 13: Discrete-Time Signals in the
Frequency Domain
13.1 Introduction
In the previous two exercises you dealt with the time-domain representation of discrete-time
signals and systems, and investigated their properties. Further insight into the properties of
such signals and systems is obtained by their representation in the frequency-domain. To
this end three commonly used representations are the discrete-time Fourier transform
(DTFT), the discrete Fourier transform (DFT), and the z-transform. In this exercise you will
study all three representations of a discrete-time sequence.
13.2 Background Review
R3.1 The discrete-time Fourier transform (DTFT) X(ej) of a sequence x[n] is defined by

The quantity |X(ej)| is called the magnitude function and the quantity () is called the phase
function , with both functions again being real functions of . In many applications, the
Fourier transform is called the Fourier spectrum and, likewise, |X(ej)| and() are referred to
as the magnitude spectrum and phase spectrum, respectively.
R3.2 The DTFT X(ej) is a periodic continuous function in with a period 2.
R3.3 For a real sequence x[n], the real part Xre(ej) of its DTFT and the magnitude Function
|X(e
j
)|are even functions of , whereas the imaginary part Xim(ej) and thephase function () are
odd functions of .
R3.4 The inverse discrete-time Fourier transform x[n] of X(ej) is given by

R3.5 The Fourier transformX(ej) of a sequencex[n] exists ifx[n] is absolutely summable, that is,

120


R3.6 The DTFT satisfies a number of useful properties that are often uitilized in a number of
applications. A detailed listing of these properties and their analytical proofs can be found in
any text on digital signal processing. These properties can also be verified using MATLAB.
We list below a few selected properties that will be encountered later in this exercise.
Time-Shifting Property If G(ej) denotes the DTFT of a sequence g[n], then the DTFT of the
time-shifted sequence g[n no] is given by ejnoG(ej).
Frequency-Shifting Property If G(ej) denotes the DTFT of a sequence g[n], then the DTFT of
the sequence ejong[n] is given by G(ej(o)).
Convolution Property If G(ej) andH(ej) denote the DTFTs of the sequences g[n] and h[n],
respectively, then the DTFT of the sequence g[n] h[n] is given by G(ej)H(ej).
Modulation Property If G(ej) and H(ej) denote the DTFTs of the sequences g[n] and h[n],
respectively, then the DTFT of the sequence g[n]h[n] is given by

Time-Reversal Property If G(ej) denotes the DTFT of a sequence g[n], then the DTFT of the
time-reversed sequence g[n] is given by G(ej).
R3.7 The N-point discrete Fourier transform (DFT) of a finite-length sequence x[n],defined for
0 n N 1, is given by

R3.8 TheN-point DFTX[k] of a length-N sequence x[n], n = 0, 1, . . . , N1, is simply the
frequency samples of its DTFT X(ej) evaluated at N uniformly spaced frequency points,
= k= 2k/N, k = 0, 1, . . . , N 1, that is,

R3.9 The N-point circular convolution of two length-N sequences g[n] and h[n], 0 n N 1, is
defined by

where _n_N = n moduloN. TheN-point circular convolution operation is usually denoted as

121


R3.10 The linear convolution of a length-N sequence g[n], 0 n N 1, with alength-M
sequence h[n], 0 n M 1, can be obtained by a (N + M 1)-point circular convolution of two
length-(N +M 1) sequences, ge[n] and he[n],

where ge[n] and he[n] are obtained by appending g[n] and h[n] with zero-valued samples:

R3.11 The DFT satisfies a number of useful properties that are often utilized in a number of
applications. A detailed listing of these properties and their analytical proofs can be found in
any text on digital signal processing. These properties can also be verified using MATLAB.
We list below a few selected properties that will be encountered later in this exercise.
Circular Time-Shifting Property IfG[k] denotes theN-point DFT of a length-N sequenceg[n],
then the N-point DFT of the circularly time-shifted sequence g[<n n
o
>
N
] is given by W
kno
N

G[k] where W
N
= e

j2/N
.
Circular Frequency-Shifting Property If G[k] denotes the N-point DFT of a length-N
sequence g[n], then the N-point DFT of the sequence W

k
o
n
N
g[n] is given byG[<kko>
N
].
Circular Convolution Property If G[k] and H[k] denote the N-point DFTs of the length-N
sequences g[n] and h[n], respectively, then the N-point DFT of the circularly convolved
sequence g[n] with h[n] is given by G[k]H[k].
Parsevals Relation If G[k] denotes the N-point DFT of a length-N sequence g[n], then


13.3 Discrete-Time Fourier Transform
The discrete-time Fourier transform (DTFT) X(ej) of a sequence x[n] is a continuous function
of . Since the data in MATLAB is in vector form, X(ej) can only be evaluated at a
prescribed set of discrete frequencies. Moreover, only a class of the DTFT that is expressed
as a rational function in ej in the form

can be evaluated. In the following two projects you will learn how to evaluate and plot the
DTFT and study certain properties of the DTFT using MATLAB.
Project 3.1 DTFT Computation
The DTFT X(e
j
) of a sequence x[n] of the form of Eq. (3.31) can be computed easily at a
prescribed set of L discrete frequency points = l using the MATLAB function freqz. Since
X(e
j
) is a continuous function of , it is necessary to make L as large as possible so that the
plot generated using the command plot provides a reasonable replica of the actual plot of

122

the DTFT. In MATLAB, freqz computes the L-point DFT of the sequences {p0 p1 . . . pM} and
{d0 d1 . . . dM}, and then forms their ratio to arrive atX(e
jl
), l= 1, 2, . . . , L. For faster
computation, L should be chosen as a power of 2, such as 256 or 512.
Program P3 1 can be used to evaluate and plot the DTFT of the form of Eq. (3.31).
% Program P3_1
% Evaluation of the DTFT
clf;
% Compute the frequency samples of the DTFT
w = -4*pi:8*pi/511:4*pi;
num = [2 1];den = [1 -0.6];
h = freqz(num, den, w);
% Plot the DTFT
subplot(2,1,1)
plot(w/pi,real(h));grid
title(Real part of H(e^{j\omega}))
xlabel(\omega /\pi);
ylabel(Amplitude);
subplot(2,1,2)
plot(w/pi,imag(h));grid
title(Imaginary part of H(e^{j\omega}))
xlabel(\omega /\pi);
ylabel(Amplitude);
pause
subplot(2,1,1)
plot(w/pi,abs(h));grid
title(Magnitude Spectrum |H(e^{j\omega})|)
xlabel(\omega /\pi);
ylabel(Amplitude);
subplot(2,1,2)
plot(w/pi,angle(h));grid
title(Phase Spectrum arg[H(e^{j\omega})])
xlabel(\omega /\pi);
ylabel(Phase, radians);
Questions:
Q3.1 What is the expression of the DTFT being evaluated in Program P3_1? What is the
function of the MATLAB command pause?






Q3.2 Run Program P3 1 and compute the real and imaginary parts of the DTFT, and the
magnitude and phase spectra . Is the DTFT a periodic function of ? If it is, what is the
period? Explain the type of symmetries exhibited by the four plots.







123


Q3.3 Modify Program P3 1 to evaluate in the range 0 the following DTFT:

and repeat Question Q3.2. Comment on your results. Can you explain the jump in the phase
spectrum ? The jump can be removed using the MATLAB command unwrap. Evaluate the
phase spectrum with the jump removed.









Q3.4 Modify Program P3 1 to evaluate the DTFT of the following finite-length sequence:
g[n]=[1 3 5 7 9 11 13 15 17],
and repeat Question Q3.2. Comment on your results. Can you explain the jumps in the
phase spectrum?








Q3.5 How would you modify Program P3 1 to plot the phase in degrees?







Project 3.2 DTFT Properties
Most of the properties of the DTFT can be verified using MATLAB. In this project you shall
verify the properties listed in R3.6. Since all data in MATLAB have to be finite-length
vectors, the sequences being used to verify the properties are thus restricted to be of finite
length.
Program P3 2 can be used to verify the time-shifting property of the DTFT.
% Program P3_2
% Time-Shifting Properties of DTFT
clf;
w = -pi:2*pi/255:pi; wo = 0.4*pi; D = 10;
num = [1 2 3 4 5 6 7 8 9];
h1 = freqz(num, 1, w);
h2 = freqz([zeros(1,D) num], 1, w);

124

subplot(2,2,1)
plot(w/pi,abs(h1));grid
title(Magnitude Spectrum of Original Sequence)
subplot(2,2,2)
plot(w/pi,abs(h2));grid
title(Magnitude Spectrum of Time-Shifted Sequence)
subplot(2,2,3)
plot(w/pi,angle(h1));grid
title(Phase Spectrum of Original Sequence)
subplot(2,2,4)
plot(w/pi,angle(h2));grid
title(Phase Spectrum of Time-Shifted Sequence)

Questions:
Q3.6Modify Program P3_2 by adding appropriate comment statements and program
statements for labeling the two axes of each plot being generated by the program. Which
parameter controls the amount of time-shift?






Q3.7Run the modified program and comment on your results.





Q3.8Repeat Question Q3.7 for a different value of the time-shift.





Q3.9Repeat Question Q3.7 for two different sequences of varying lengths and two different
time-shifts.





Program P3 3 can be used to verify the frequency-shifting property of the DTFT.
% Program P3_3
% Frequency-Shifting Properties of DTFT
clf;
w = -pi:2*pi/255:pi; wo = 0.4*pi;
num1 = [1 3 5 7 9 11 13 15 17];

125

L = length(num1);
h1 = freqz(num1, 1, w);
n = 0:L-1;
num2 = exp(wo*i*n).*num1;
h2 = freqz(num2, 1, w);
subplot(2,2,1)
plot(w/pi,abs(h1));grid
title(Magnitude Spectrum of Original Sequence)
subplot(2,2,2)
plot(w/pi,abs(h2));grid
title(Magnitude Spectrum of Frequency-Shifted Sequence)
subplot(2,2,3)
plot(w/pi,angle(h1));grid
title(Phase Spectrum of Original Sequence)
subplot(2,2,4)
plot(w/pi,angle(h2));grid
title(Phase Spectrum of Frequency-Shifted Sequence)
Questions:
Q3.10 Modify Program P3_3 by adding appropriate comment statements and program
statements for labeling the two axes of each plot being generated by the program. Which
parameter controls the amount of frequency-shift?





Q3.11 Run the modified program and comment on your results.





Q3.12 Repeat Question Q3.11 for a different value of the frequency-shift.





Q3.13 Repeat Question Q3.11 for two different sequences of varying lengths and two
different frequency-shifts.




Program P3 4 can be used to verify the convolution property of the DTFT.
% Program P3_4
% Convolution Property of DTFT
clf;

126

w = -pi:2*pi/255:pi;
x1 = [1 3 5 7 9 11 13 15 17];
x2 = [1 -2 3 -2 1];
y = conv(x1,x2);
h1 = freqz(x1, 1, w);
h2 = freqz(x2, 1, w);
hp = h1.*h2;
h3 = freqz(y,1,w);
subplot(2,2,1)
plot(w/pi,abs(hp));grid
title(Product of Magnitude Spectra)
subplot(2,2,2)
plot(w/pi,abs(h3));grid
title(Magnitude Spectrum of Convolved Sequence)
subplot(2,2,3)
plot(w/pi,angle(hp));grid
title(Sum of Phase Spectra)
subplot(2,2,4)
plot(w/pi,angle(h3));grid
title(Phase Spectrum of Convolved Sequence)
Questions:
Q3.14Modify Program P3 4 by adding appropriate comment statements and program
statements for labeling the two axes of each plot being generated by the program.






Q3.15Run the modified program and comment on your results.






Q3.16Repeat Question Q3.15 for two different sets of sequences of varying lengths.






Program P3 5 can be used to verify the modulation property of the DTFT.
% Program P3_5
% Modulation Property of DTFT
clf;
w = -pi:2*pi/255:pi;
x1 = [1 3 5 7 9 11 13 15 17];

127

x2 = [1 -1 1 -1 1 -1 1 -1 1];
y = x1.*x2;
h1 = freqz(x1, 1, w);
h2 = freqz(x2, 1, w);
h3 = freqz(y,1,w);
subplot(3,1,1)
plot(w/pi,abs(h1));grid
title(Magnitude Spectrum of First Sequence)
subplot(3,1,2)
plot(w/pi,abs(h2));grid
title(Magnitude Spectrum of Second Sequence)
subplot(3,1,3)
plot(w/pi,abs(h3));grid
title(Magnitude Spectrum of Product Sequence)
Questions:
Q3.17 Modify Program P3 5 by adding appropriate comment statements and program
statements for labeling the two axes of each plot being generated by the program.





Q3.18 Run the modified program and comment on your results.





Q3.19 Repeat Question Q3.18 for two different sets of sequences of varying lengths.





Program P3 6 can be used to verify the time-reversal property of the DTFT.
% Program P3_6
% Time-Reversal Property of DTFT
clf;
w = -pi:2*pi/255:pi;
num = [1 2 3 4];
L = length(num)-1;
h1 = freqz(num, 1, w);
h2 = freqz(fliplr(num), 1, w);
h3 = exp(w*L*i).*h2;
subplot(2,2,1)
plot(w/pi,abs(h1));grid
title(Magnitude Spectrum of Original Sequence)
subplot(2,2,2)
plot(w/pi,abs(h3));grid

128

title(Magnitude Spectrum of Time-Reversed Sequence)
subplot(2,2,3)
plot(w/pi,angle(h1));grid
title(Phase Spectrum of Original Sequence)
subplot(2,2,4)
plot(w/pi,angle(h3));grid
title(Phase Spectrum of Time-Reversed Sequence)
Questions:
Q3.20 Modify Program P3 6 by adding appropriate comment statements and program
statements for labeling the two axes of each plot being generated by the program. Explain
how the program implements the time-reversal operation.






Q3.21 Run the modified program and comment on your results.







Q3.22 Repeat Question Q3.21 for two different sequences of varying lengths.

129

Lab 14: Discrete Fourier Transform
The discrete Fourier transform (DFT) X[k] of a finite-length sequence x[n] can be easily
computed in MATLAB using the function fft. There are two versions of this function.fft(x)
computes the DFT X[k] of the sequence x[n] where the length of X[k] is the same as that of
x[n]. fft(x,L) computes the L-point DFT of a sequence x[n] of lengthN whereL N. IfL > N,
x[n] is zero-padded with LN trailing zero-valued samples before the DFT is computed. The
inverse discrete Fourier transform (IDFT) x[n] of a DFT sequence X[k] can likewise be
computed using the function ifft, which also has two versions.
Project 3.3 DFT and IDFT Computations
Questions:
Q3.23 Write a MATLAB program to compute and plot the L-point DFT X[k] of a sequence
x[n] of length N with L N and then to compute and plot the L-point IDFT of X[k]. Run the
program for sequences of different lengths N and for different values of the DFT length L.
Comment on your results.








Q3.24 Write a MATLAB program to compute the N-point DFT of two length-N real
sequences using a single N-point DFT and compare the result by computing directly the two
N-point DFTs.







Q3.25 Write a MATLAB program to compute the 2N-point DFT of a length-2N real sequence
using a single N-point DFT and compare the result by computing directly the2N-point DFT.





Project 3.4 DFT Properties
Two important concepts used in the application of the DFT are the circular-shift of a
sequence and the circular convolution of two sequences of the same length. As these

130

operations are needed in verifying certain properties of the DFT, we implement them as
MATLAB functions circshift1 and circonv as indicated below:
function y = circshift1(x,M)
% Develops a sequence y obtained by
% circularly shifting a finite-length
% sequence x by M samples
if abs(M) > length(x)
M = rem(M,length(x));
end
if M < 0
M = M + length(x);
End
y = [x(M+1:length(x)) x(1:M)];}
function y = circonv(x1,x2)
L1 = length(x1); L2 = length(x2);
if L1 ~= L2, error(Sequences of unequal lengths), end
y = zeros(1,L1);
x2tr = [x2(1) x2(L2:-1:2)];
for k = 1:L1
sh = circshift1(x2tr,1-k);
h = x1.*sh;
y(k) = sum(h);
end
Questions:
Q3.26 What is the purpose of the command rem in the function circshift1?





Q3.27 Explain how the function circshift1 implements the circular time-shifting operation.





Q3.28 What is the purpose of the operator ~= in the function circonv?




Q3.29 Explain how the operation of the function circonv implements the circular
convolution operation.






131

Program P3 7 can be used to illustrate the concept of circular shift of a finite-length
sequence. It employs the function circshift1.
% Program P3_7
% Illustration of Circular Shift of a Sequence
clf;
M = 6;
a = [0 1 2 3 4 5 6 7 8 9];
b = circshift1(a,M);
L = length(a)-1;
n = 0:L;
subplot(2,1,1);
stem(n,a);axis([0,L,min(a),max(a)]);
title(Original Sequence);
subplot(2,1,2);
stem(n,b);axis([0,L,min(a),max(a)]);
title([Sequence Obtained by Circularly Shifting by
,num2str(M),Samples]);
Questions:
Q3.30 Modify Program P3 7 by adding appropriate comment statements and program
statements for labeling each plot being generated by the program. Which parameter
determines the amount of time-shifting? What happens if the amount of time-shift is greater
than the sequence length?





Q3.31 Run the modified program and verify the circular time-shifting operation.




Program P3 8 can be used to illustrate the circular time-shifting property of the DFT. It
employs the function circshift1.
% Program P3_8
% Circular Time-Shifting Property of DFT
clf;
x = [0 2 4 6 8 10 12 14 16];
N = length(x)-1; n = 0:N;
y = circshift1(x,5);
XF = fft(x);
YF = fft(y);
subplot(2,2,1)
stem(n,abs(XF)); grid
title(Magnitude of DFT of Original Sequence);
subplot(2,2,2)
stem(n,abs(YF)); grid
title(Magnitude of DFT of Circularly Shifted Sequence);
subplot(2,2,3)

132

stem(n,angle(XF)); grid
title(Phase of DFT of Original Sequence);
subplot(2,2,4)
stem(n,angle(YF)); grid
title(Phase of DFT of Circularly Shifted Sequence);
Questions:
Q3.32 Modify Program P3 8 by adding appropriate comment statements and program
statements for labeling each plot being generated by the program. What is the the amount of
time-shift?





Q3.33 Run the modified program and verify the circular time-shifting property of the DFT.





Q3.34 Repeat Question Q3.33 for two different amounts of time-shift.





Q3.35 Repeat Question Q3.33 for two different sequences of different lengths.





Program P3 9 can be used to illustrate the circular convolution property of the DFT. It
employs the function circonv.
% Program P3_9
% Circular Convolution Property of DFT
g1 = [1 2 3 4 5 6]; g2 = [1 -2 3 3 -2 1];
ycir = circonv(g1,g2);
disp(Result of circular convolution = );disp(ycir)
G1 = fft(g1); G2 = fft(g2);
yc = real(ifft(G1.*G2));
disp(Result of IDFT of the DFT products = );disp(yc)
Questions:
Q3.36 Run Program P3 9 and verify the circular convolution property of the DFT.





133


Q3.37 Repeat Question Q3.36 for two other different sets of equal-length sequences.





Program P3 10 can be used to illustrate the relation between circular and linear convolutions
(see R3.10).
% Program P3_10
% Linear Convolution via Circular Convolution
g1 = [1 2 3 4 5];g2 = [2 2 0 1 1];
g1e = [g1 zeros(1,length(g2)-1)];
g2e = [g2 zeros(1,length(g1)-1)];
ylin = circonv(g1e, g2e);
disp(Linear convolution via circular convolution = );disp(ylin);
y = conv(g1, g2);
disp(Direct linear convolution = );disp(y)
Questions:
Q3.38 Run Program P3 10 and verify that linear convolution can be obtained via circular
convolution.





Q3.39 Repeat Question Q3.38 for two other different sets of sequences of unequal lengths.





Q3.40 Write a MATLAB program to develop the linear convolution of two sequences via the
DFT of each. Using this program verify the results of Questions Q3.38 and Q3.39.





Program P3 11 can be used to verify the relation between the DFT of a real sequence, and the
DFTs of its periodic even and the periodic odd parts (see R3.12).
% Program P3_11
% Relations between the DFTs of the Periodic Even
% and Odd Parts of a Real Sequence
x = [1 2 4 2 6 32 6 4 2 zeros(1,247)];
x1 = [x(1) x(256:-1:2)];
xe = 0.5 *(x + x1);
XF = fft(x);

134

XEF = fft(xe);
clf;
k = 0:255;
subplot(2,2,1);
plot(k/128,real(XF)); grid
ylabel(Amplitude);
title(Re(DFT\{x[n]\}));
subplot(2,2,2);
plot(k/128,imag(XF)); grid ylabel(Amplitude);
title(Im(DFT\{x[n]\}));
subplot(2,2,3);
plot(k/128,real(XEF)); grid
xlabel(Time index n); ylabel(Amplitude);
title(Re(DFT\{x_{e}[n]\} ));
subplot(2,2,4);
plot(k/128,imag(XEF)); grid
xlabel(Time index n);ylabel(Amplitude);
title(Im(DFT\{x_{e}[n]\}));
Questions:
Q3.41 What is the relation between the sequences x1[n] and x[n]?







Q3.42 Run Program P3 11. The imaginary part of XEF should be zero as the DFT of the
periodic even part is simply the real part of XEF of the original sequence. Can you verify
that? How can you explain the simulation result?










Q3.43 Modify the program to verify the relation between the DFT of the periodic odd part
and the imaginary part of XEF.







135



Parsevals relation (Eq. (3.15)) can be verified using the following program.
% Program P3_12
% Parsevals Relation
x = [(1:128) (128:-1:1)];
XF = fft(x);
a = sum(x.*x)
b = round(sum(abs(XF).^2)/256})

Questions:
Q3.44 Run Program P3 12. Do you get the same values for a and b?






Q3.45 Modify the program in such a way that you do not have to use the command abs(XF).
Use the MATLAB command conj(x) to compute the complex conjugate of x.


136

Si ne Wave1
Si ne Wave
Scope
Product
2
Constant
Message Signal
Carrier Signal
Amplitude Modulation (AM) SIgnal
Lab 15: Introduction to SIMULINK
15.1 AMPLITUDE MODULATION











MATLAB Implementation (Coding) Of Amplitude Modulation
Amplitude Modulation
ts=1e-3;
a=2;
t=-2:ts:2;
fm=1;
fc=15;
wm=2*pi*fm;
wc=2*pi*fc;
message=sin(wm*t);
carrier=cos(wc*t);
am=(a+message).*carrier;
subplot(311);
plot(t,message);
xlabel('Message Signal');
subplot(312);
plot(t,carrier);
xlabel('Carrier Signal');
subplot(313);
plot(t,am);
xlabel('Amplitude Modulated (AM) Signal');
15.1.1 SIMULINK IMPLEMENTATION OF AMPLITUDE MODULATION
Example # 1















137

AM = (A + message) * Carrier A

The above is the block diagram for AM (amplitude modulation) in SIMULINK. We have to
implement equation A
Message Signal: fm=1 Hz, wm=2fm, phase = 0
Carrier Signal: fc=1 Hz, wm=2fc, phase = 0
Sample Time: 1e-3 for both message and carrier signal
Scope: Number of axis = 3
Simulation Parameters: Start time = -2, Stop time = 2
Sine Type: Time based, Amplitude = 1;
15.2 TRIGNOMETRIC FOURIER SERIES (TFS)
Example # 1:




138

In previous Labs we implemented above square wave using Fourier series expansion. In
this lab we will do it in SIMULINK but we will add up to 9 harmonics.
The general equation of above square wave was found in Lab 4 to be
1 2 1 1 1 1
( ) 3 5 7 9 ... cos cos cos cos cos
2 3 5 7 9
O O O O O
w t w t w t w t w t w t
t
| |
= + + + +
|
\ .

Wo = 1

We have to implement the above equation up till 9Wot and see the output in simulink.
So we require 5 sine wave blocks and 1 constant block of value 1/2. Cosine is
implemented by giving sine a phase shift of






15.2.1 SIMULINK IMPLEMENTATION







Simulink parameters

Start time = -15
Stop time = +15

Phase = pi/2 for all sine blocks

Sample time 1e^-3 for all sine blocks

Frequency (rad/sec) 1,3,5,7,9

Amplitude 2/pi, -2/3pi, 2/5pi, -2/7pi, 2/9pi


139

Das könnte Ihnen auch gefallen