You are on page 1of 10

Islamic University of Gaza

Faculty of Engineering
Electrical Engineering Department
2012
_________________________________________________________________________________

DSP Laboratory (EELE 4110)


Lab#1 Introduction to Matlab

Goals for this Lab Assignment:


In this lab we would have an introduction to MAT LAB and get started with working in its
wonderfully simple environment. This lab, as a matter of fact, would lay the foundation for our next
labs. In the following paragraphs, you are provided with a tutorial on MATLAB. In addition, well go
over a detailed introduction to MATLAB in our first discussion session. This would enable you to do
simple but useful things in MATLAB.

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

%creates a 1x4 vector with elements 1, 3, 5 and 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.

Here are some examples.


Z = zeros(2,4)
Z=
0000
0000
N = fix(10*rand(1,10))
N=
4944852680
R = randn(4,4)
R=
1.0668 0.2944
0.0593 -1.3362
-0.0956 0.7143
-0.8323
1.6236

-0.6918
0.8580
1.2540
-1.5937

-1.4410
0.5711
-0.3999
0.6900

The Colon Operator


The colon, : , is one of the most important MATLAB operators. It occurs in several different forms.
The expression 1:10 is a row vector containing the integers from 1 to 10, i.e. 1 2 3 4 5 6 7 8 9 10
To obtain non-unit spacing, specify an increment. For example,
100:-7:50

% a row vector containing the integers

100 93 86 79 72 65 58 51

Subscript expressions involving colons refer to portions of a matrix.


A(1:k,j)
sum(A(1:4,4))

% the first k elements of the jth column of A. So


%computes the sum of the fourth column.

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

>> X=[1 2 3;6 7 8]


>> [m,n] = size(X) % returns the size of matrix X in separate variables m and n.
>> x = ones(1,8);
>> n = length(x)
% will assign the value 8 to n

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

Scripts and Functions


MATLAB is a powerful programming language as well as an interactive computational environment.
Files that contain code in the MATLAB language are called M-files. You create M-files using a text
editor, and then use them as you would use any other MATLAB function or command.
There are two kinds of M-files:
Scripts, which do not accept input arguments or return output arguments. They
operate on data in the workspace.
Functions, which can accept input arguments and return output arguments. Internal
variables are local to the function.
Scripts
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can
operate on existing data in the workspace, or they can create new data on which to operate. Although
scripts do not return output arguments, any variables that they create remain in the workspace, to be
used in subsequent computations. In addition, scripts can produce graphical output using functions
like plot.
For example, create a file called modify.m that contains these MATLAB commands.
r = rand(1,10)
r(1:2:length(r))=0;
y=r
modify
causes MATLAB to execute the commands, change the value of the odd indexed elements of vector r
to zero, and assign the result to y . After execution of the file is complete, the variables y and r remain
in the workspace.

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)

Multiple Data Sets in One Graph


Multiple x-y pair arguments create multiple graphs with a single call to plot. MATLAB automatically
cycles through a predefined list of colors to allow discrimination among sets of data. For example,
these statements plot three related functions of x, each curve in a separate distinguishing color.
x= 0:pi/40:2*pi;
y= sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
plot(x,y,x,y2,x,y3)
legend('sin(x)','sin(x-.25)','sin(x-.5)')
% The legend command provides an easy way to identify the individual plots.
Axis rescaling:
MATLAB provides automatic scaling. The command axis([x min. x max. ymin. y max.]) enforces
the manual scaling. For example
axis([-10 40 -inf inf])
produces an x-axis scale from - 10 to 40 and an automatic scaling for the y-axis scale. Typing axis
again or axis(auto) resumes auto scaling.
Stem
If you wish to use information in discrete-time using the stem command can be useful. It is very
similar to plot except it doesnt connect the dots.
The following example creates a stem plot of a cosine function.
y = linspace(0,2*pi,10);
h = stem(cos(y),'fill','-.');
set(h(3),'Color','r','LineWidth',2) % Set base line properties
axis ([0 11 -1 1])

Specifying Line Styles and Colors


It is possible to specify color, line styles, and markers (such as plus signs or circles) when you plot
your data using the plot command.
plot(x,y,'color_style_marker') , where color_style_marker is a string containing from one to four
characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker
type:

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.

Adding Plots to an Existing Graph


The hold command enables you to add plots to an existing graph. When you type
hold on
MATLAB does not replace the existing graph when you issue another plotting command; it adds the
new data to the current graph, rescaling the axes if necessary. To remove the effect of the hold on
function you may use:
hold off
Multiple Plots in One Figure
The subplot command enables you to display multiple plots in the same window or print them on the
same piece of paper. Typing:
subplot(m,n,p)
partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for
the current plot. The plots are numbered along first the top row of the figure window, then the second
row, and so on. For example, these statements plot data in four different subregions of the figure
window.
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)

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.

Playing Sound Files from MatLab Data


Digital signal processing is widely used in speech processing for applications ranging from speech
compression and transmission, to speech recognition and speaker identification. This exercise will
introduce the process of reading and manipulating a speech signal.
Once you have a .wav file, you can read the data into your program using MATLAB's wavread
function.. You must determine the file path first. After you read the wave file, the soundsc function
gives you the ability to hear the wave.
[x, fs] = wavread('file path\file name');
soundsc(x, fs);
MatLab may be used to convert the available Ascii files into .wav format. This permits the original
sounds to be heard using the Sound Recorder application, for example. If an Ascii version of a
sound file is loaded into MatLab, then a .wav file may be created using the wavwrite command. The
sampling frequency must be specified to use this function, for example:
wavwrite(x,22255,'mysound.wav') % x: vector containing speech samples, 22255: sampling rate

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.

Read this wave file using wavread function.


Listen to the wave using soundsc function.
Create a *.wav file that contains a flipped version of speech_dft.wav
What are the sampling frequency, length, and size of the wave?
Sketch its spectrum.

Useful Facts in MATLAB


1. MATLAB starts indexing its arrays from 1 rather than from 0.
2. The end keyword is exceptionally useful when indexing into arrays of unknown size.
Thus, if you want to return all elements in a vector except the first and last one, you
can use the command:
>> x(2:end-1) %equivalent to x(2:length(x)-1)
3. MATLAB automatically resizes arrays for you. Thus, if you want to add an element on
to the end of a vector, you can use the command:
>> x(end+1) = 5;

10

You might also like