Matlab Tutorial F09
Matlab Tutorial F09
Fall 2009
1 Motivation
Matlab is a ubiquitous computing environment used by the scientific community. It is designed
to manipulate, visualize and organize large amounts of data, making it especially powerful for
the following tasks:
In 6.341 and many fields of interest, computations are done in discrete time. Thus, we can
abstract any information stream as a vector or array of values. From this document, I hope
to show that Matlab is an intuitive and powerful way to consider problems signal processing.
The projects will be done in Matlab so it is imperative that you become comfortable with the
program and understand how to perform many common tasks.
bottom left window (3) is the Command History, making it easy to recall commands you have
used previously.
As with most environments, there are other options and customizations that make the
Matlab desktop easier to navigate. Take a few minutes to explore it.
x = 5
You will immediately see that the console will echo the result.
x =
5
Moreover, the variable x will now appear in the workspace and the command history. Now
consider the following commands and the console response (>> indicate a command and are
automatically included by the console. Don’t enter >> yourself):
>> x = 5
x =
>> y = x
y =
>> y = '6.341';
There are a few things to note in these three simple commands. Firstly, you can initialize
variables to functions of other variables. By letting y = x, I did indeed set y = 5. Secondly,
you can create strings by placing single quotation marks around the text, like when I set y =
‘6.341’. Note that y dynamically changed from being an int type to a string type. Matlab
takes care of this so we do not have to worry about it. Finally, to suppress the echo from
the console, you can add a semicolon after the command. Creating vectors and matrices in
Matlab is just as easy. To make a vector, one can type the command
>> A = [6 3 4 1]
A =
6 3 4 1
>> B = 3:6
B =
3 4 5 6
>> C = 0:5:20
C =
0 5 10 15 20
The leftmost and rightmost values indicate the upper and lower bounds of the vector. The
optional step value indicates how much to increment the next term.
Finally, we can make matrices in the same fashion as vectors, except we need a semicolon
to indicate when to move onto the next row. An example is given below:
>> D = [3 4 1; 4 1 8; 9 6 5]
D =
3 4 1
4 1 8
9 6 5
Taking everything we have learned thus far, we can make vectors and arrays by concatenat-
ing other variables. Try the following set of commands and see if they work as expected.
A = [5 2:5]
B = [0 0 A]
C = [2; 3; 5; 9]
M = [A; 5:2:13; 1 2 3 4 5]
N = [M [99; 98; 97]]
Matlab also allows you to consider subsets of a vector or matrix. Try the following exam-
ples to get a flavor of what you can do.
A(1)
A(1:3)
B(4,1)
C(1,4)
M(1,3)
M(1:3,2:3)
M(:,1)
M(12)
N(1,:)
Only one parameter is necessary, even for matrices. For this case, indices increase down
the column and then to the next column. Also, the colon in Matlab syntax indicates all the
values of that particular row or column.
x = 5+2
y = 2/4 + 5/3 + x
4*y + 2ˆ2 − 4/3*2
There is some specific ordering in which operations are being performed. Brackets can be
used to make sure that you get the ordering that you want.
More complex operators are available but must be implemented as functions. Thus, you
must enter in parameters when calling them. You can also access the Matlab Help to get
more information about the function. Oftentimes not all parameters need to be specified.
Some examples are given below.
help sin
xsin = sin(x)
p = exp(x)*log(y)*pow(xsin,4);
sin(log(200))
Matlab ’s true power is its power to handle vectors and matrices as variables. Thus, it is
just as easy to operate on vectors as it is for scalars. Try the following commands:
x = [1:10]
y = [2:2:20];
x + y
sin(y)
ymax = max(y)
fliplr(y)
Some nuances exist in the multiplication and division of matrices and vectors. Those who
have taken linear algebra will know that matrix multiplication is not the same as point-by-
point multiplication of the terms. In Matlab , one can do matrix (or vector) multiplication
by using the * character. However, if one wants to do point-by-point multiplication (meaning
multiplying the corresponding values in each matrix), then you should add a period right before
the *. The following commands motivate this point:
X = [1 2; 4 5];
Y = [1 0; 0 1];
Z1 = X*Y
Z2 = X.*Y
V1 = Xˆ2
V2 = X.ˆ2
Try some more commands and get comfortable with creating variables. Also, think of
different operators that you could apply and use the Matlab help to find out if a function
exists for it.
Figure 2: The Matlab desktop
t = [−3:.001:3];
y = sin(5*t);
plot(t,y);
Note a semicolon is added after initializing the time vector. This is because the vector is
very long (6001 terms) and I did not want to display it on the console. The plot should look
like this:
This graph can be exported to many image formats to fit your needs. Other functions can
allow you to customize this image. Some examples are listed below.
plot(t, y, 'r:');
axis([−2 2 0 1]);
title('This is a sine curve');
xlabel('time');
ylabel('amplitude');
Use the Matlab Help documentation, especially on the plot function. There are a lot of
options that can be used to make plots look nicer. It is also possible to add several curves into
the same graph. One can do the following:
t = [−3:.001:3];
x = sin(5*t);
y = cos(3*t);
plot(t, x, t, y);
t = [−3:.001:3];
x = sin(5*t);
y = cos(3*t);
plot(t,x, 'k:');
hold on
plot(t, y, 'r−');
hold off
You can also draw several graphs (referred to in Matlab jargon as figures). To add a new
figure, use the figure command. You can also add a number parameter such as figure(3) if
you want to keep track of which figures you are accessing. A sample chunk of code is given to
illustrate working with multiple figures.
t = [−3:.001:3];
x = sin(5*t);
plot(t,x);
figure;
y = cos(3*t);
plot(t,y);
figure(50);
z = 3*t;
plot(t, z);
The input and output variables are optional. Note that the % denotes a comment. A nything
following the % character is not run. It can be useful to document your work.
A function with parameters must be run in the console (or accessed by other scripts and
functions). Again, you can simply type the function’s name as the command. To call the above
function, just run
y = tempFunc( 5, 3);
Through this course and others you will take involving Matlab , you will be asked to write
scripts and functions. Try to make a conscious effort to use them as much as possible. This
will make it much easier to troubleshoot problems and help you modularize the code, which
will become very important as the Matlab tasks become more complex.
a = [2 0 3 0];
y = a > 0
4. Concepts that you learned in C or Java is also applicable in Matlab . The help docu-
mentation can show you how to add for loops, while loops and switch statements.
5. For debugging purposes, especially when writing scripts or functions, it may be good to
output some text to the console. Use the fprintf or display functions for this.
6. Two very useful functions for making vectors and arrays are the zeros and ones functions.
They will generate a sequence of zeros or ones depending on your input specifications.
OUT = (BW > thres); % set thres: if pixel > thres, then out = 1
figure(2)
imshow(OUT); % take a look at the thresholded image
imwrite(OUT,'out.jpg','jpg'); % now write to file
end
8 Conclusion
In my previous teaching experience, I have found that Matlab is a major stumbling block
for students, who find it intimidating. However, Matlab has a very gentle learning curve and
can be a very useful tool in manipulating and visualizing data. This document is designed to
introduce you to the program but is not an exhaustive overview. There are other resources on
the web, including the surprisingly effective MathWorks documentation. Moreover, I and the
other members of the teaching staff would be happy to discuss any questions you may have. In
the end, the best way to learn how to use Matlab is through experience.