DSP Laboratory (EELE 4110) : Lab#1 Introduction To Matlab
DSP Laboratory (EELE 4110) : Lab#1 Introduction To Matlab
DSP Laboratory (EELE 4110) : Lab#1 Introduction To Matlab
Faculty of Engineering
Electrical Engineering Department
2012
_________________________________________________________________________________
Workspace Browser
The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB
session and stored in memory. You add variables to the workspace by using functions, running Mfiles, and loading saved workspaces. To view the workspace and information about each variable, use
the Workspace browser, or use the functions who and whos.
To delete variables from the workspace, select the variable and select Delete from the Edit menu.
Alternatively, use the clear function. The workspace is not maintained after you end the MATLAB
session. To save the workspace to a file that can be read during a later MATLAB session, select
Save Workspace As from the File menu, or use the save function. This saves the workspace to a
binary file called a MAT-file, which has a .mat extension. There are options for saving to different
formats. To read in a MAT-file, select Import Data from the File menu, or use the load function.
You will use this function to load a wave signal later in this lab.
Array Editor
Double-click a variable in the Workspace browser to see it in the Array Editor. Use the Array Editor
to view and edit a visual representation of one- or two-dimensional numeric arrays, strings, and cell
arrays of strings that are in the workspace.
1
Search Path
MATLAB uses a search path to find M-files and other MATLAB-related files, which are organized in
directories on your file system. Any file you want to run in MATLAB must reside in the current
directory or in a directory that is on the search path. Add the directories containing files you create to
the MATLAB search path. By default, the files supplied with MATLAB and MathWorks toolboxes
are included in the search path. To see which directories are on the search path or to change the
search path, select Set Path from the File menu in the desktop, and use the Set Path dialog box.
Definition of Matrices
MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore,
vector and matrix operations are as simple as common "calculator operations".
Vectors can be defined in two ways. The first method is used for arbitrary elements:
v = [1 3 5 7];
Note that commas could have been used in place of spaces to separate the elements. Additional
elements can be added to the vector:
v(5) = 8;
Matrices are defined by entering the elements row by row:
M = [1 2 4; 3 6 8];
1 2 4
3 6 8
There are a number of special matrices that can be defined:
null matrix:
M = [ ];
nxm matrix of zeros:
M = zeros(n,m);
nxm matrix of ones:
M = ones(n,m);
nxn identity matrix:
M = eye(n);
Uniformly distributed random elements M = rand(n,m);
Normally distributed random elements M = randn(n,m);
A particular element of a matrix can be assigned:
M(1,2) = 5; % places the number 5 in the first row, second column.
-0.6918
0.8580
1.2540
-1.5937
-1.4410
0.5711
-0.3999
0.6900
100 93 86 79 72 65 58 51
But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix
and the keyword end refers to the last row or column. So
sum(A(:,end)) %computes the sum of the elements in the last column of A.
Exercise 1
1. Generate a matrix of size 3x3 of normally distributed
random numbers.
2. Change the value of the 3 rd column to [6 9 2].
3. Delete the 2nd row.
Dimension Functions
Dimensioning is automatic in MATLAB. You can find the dimensions of an existing matrix with the
size. Also the command length(x) returns the length of the vector x
Concatenation:
Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your
first matrix by concatenating its individual elements. The pair of square brackets, [ ], is the
concatenation operator. To do so horizontally, we separate the arrays with spaces or commas:
>> [ones(2,3), zeros(2,3)]
To do so vertically, we separate the arrays with a semicolon:
>> [ones(2,3); zeros(2,3)]
Exercise 2
1. Generate 4-by-4 ones matrix, A.
2. Then form B = [A A+30; A+40 A+16]
3. Whats the size of B?
Exercise 3
Define the following discrete time signal
3 0n 5
x [n ] 1 5 n 15
2 15 n 20
Functions
Functions are M-files that can accept input arguments and return output arguments. The name of the
M-file and of the function should be the same. Functions operate on variables within their own
workspace, separate from the workspace you access at the MATLAB command prompt.
Global Variables
If you want more than one function to share a single copy of a variable, simply declare the variable as
global in all the functions. Do the same thing at the command line if you want the base workspace to
access the variable. The global declaration must occur before the variable is actually used in a
function. Although it is not required, using capital letters for the names of global variables helps
distinguish them from other variables. For example, create an M-file called falling.m.
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Then interactively enter the statements in MATLAB command window
global GRAVITY
GRAVITY = 32;
y = falling((0:0.1:5)');
The two global statements make the value assigned to GRAVITY at the command prompt available
inside the function. You can then modify GRAVITY interactively and obtain new solutions without
editing any files.
It is worth mentioned that when a function returns multiple parameters, we use square brackets to
retrieve them:
>> [max_value, index] = max([4.3, 2.9, 8.6, 6.3, 1.0])
Otherwise, only one parameter is returned
Representing Polynomials
MATLAB represents polynomials as row vectors containing coefficients ordered by descending
powers. For example, consider the equation
p ( x) x 3 2 x 5
To enter this polynomial into MATLAB, use
p = [1 0 -2 -5];
Polynomial Roots
The roots function calculates the roots of a polynomial.
r = roots(p)
r=
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i
By convention, MATLAB stores roots in column vectors. The function poly returns to the polynomial
coefficients.
p2 = poly(r)
p2 =
1 8.8818e-16 -2 5
So the poly and roots are inverse functions.
5
Polynomial Evaluation
The polyval function evaluates a polynomial at a specified value. To evaluate p at s = 5, use
polyval(p,5)
ans =
110
It is also possible to evaluate a polynomial in a matrix sense. In this case p( x) x 3 2 x 5
becomes p ( X ) X 3 2 X 5 I , where X is a square matrix and I is the identity matrix. For
example, create a square matrix X and evaluate the polynomial p at X.
X = [2 4 5; -1 0 3; 7 1 5];
Y = polyvalm(p,X)
Y=
377 179 439
111 81 136
490 253 639
Exercise 4
Consider the polynomial p ( x) x 4 5 x 3 7 x 10
1. Find the roots of this polynomial.
2. From these roots, reconstruct p(x).
3. Find the value of p(x) at x=3.
4. Evaluate the polynomial at X (matrix sense).
Graphics in MATALB:
Creating a Plot
The plot function has different forms, depending on the input arguments. If y is a vector, plot(y)
produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you
specify two vectors as arguments, plot(x,y) produces a graph of y versus x.
For example, these statements use the colon operator to create a vector of x values ranging from zero
to 2, compute the sine of these values, and plot the result.
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
%Now label the axes and add a title. The characters \pi create the symbol .
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These correspond to cyan, magenta,
yellow, red, green, blue, white, and black.
Linestyle strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for dash-dot. Omit
the linestyle for no line.
The marker types are '+', 'o', '*', and 'x' and the filled marker types are 's' for square,
'd' for diamond, '^' for up triangle, 'v' for down triangle, '>' for right triangle, '<' for
left triangle, 'p' for pentagram, 'h' for hexagram, and none for no marker.
Figure Windows
Graphing functions automatically open a new figure window if there are no figure windows already
on the screen. If a figure window exists, MATLAB uses that window for graphics output. If there are
multiple figure windows open, MATLAB targets the one that is designated the current figure (the
last figure used or clicked in).
To make an existing figure window the current figure, you can type :
>> figure(n)
where n is the number in the figure title bar. The results of subsequent graphics commands are
displayed in this window. To open a new figure window and make it the current figure, type:
>> figure
Consider the following MATLAB script:
dB=0:0.1:10;
SNR=10.^(dB./10);
Pb=0.5*erfc(sqrt(SNR))
semilogy(dB,pb) %same as plot(dB,log10(pb))
grid
xlabel(SNR(dB))
ylabel(Bit error rate)
title(Performance of antipodal signaling over AWGN)
Exercise 5
Using MATLAB, plot the function
f (t ) e 2t sin(3 t )u (t )
where t ranges from 2 to 10. Give the x-axis the title (t sec) and the
y-axis the title (f(t) volts ). Repeat using stem function. Then use
subplot to combine the two figures in one figure and give it the
name: difference between plot and stem.
Exercise 6
We will do this exercise on the wave file speech_dft.wav. You can find this file in
matlab13\toolbox\dspblks\dspblks\speech_dft.wav
1.
2.
3.
4.
5.
10