Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Matlab Tutorial F09

This document provides an introduction to Matlab, highlighting its capabilities for data manipulation, visualization, and interfacing with electronic equipment. It covers essential topics such as creating and manipulating vectors and matrices, performing computations, plotting data, and writing scripts and functions. The document aims to equip users with the fundamental skills needed for discrete-time signal processing tasks in the context of the course 6.341 at MIT.

Uploaded by

dudydudedj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Matlab Tutorial F09

This document provides an introduction to Matlab, highlighting its capabilities for data manipulation, visualization, and interfacing with electronic equipment. It covers essential topics such as creating and manipulating vectors and matrices, performing computations, plotting data, and writing scripts and functions. The document aims to equip users with the fundamental skills needed for discrete-time signal processing tasks in the context of the course 6.341 at MIT.

Uploaded by

dudydudedj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Massachusetts Institute of Technology

Department of Electrical Engineering and Computer Science

6.341: Discrete-Time Signal Processing

Fall 2009

A Brief Introduction to Matlab

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:

Doing computations using matrices

Plotting and gathering statistics about data

Interfacing between PC and various electronic equipment such as oscilloscopes

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.

2 Getting and Running Matlab


Matlab can be accessed by any computer running Athena. Moreover, a licensed student
version can be downloaded on the MIT IS&T website at http://web.mit.edu/ist/topics/math/.
Figure 1 illustrates what Matlab looks like when it is first opened on Windows machines.
This would not be the case on Linux Athena machines; a simple console window will be opened
instead. To reach the more user-friendly desktop view, simply enter the command desktop at
the console.
The first thing to note when opening Matlab is the little bar at the very top indicating the
Current Directory. Although Matlab can easily access scripts, data files or media anywhere
on the PC, it is convenient to set the current directory to a stable location where you have
permissions. In the Athena machines, it would be ideal to set this to your Athena home
directory.
Now let’s look at the desktop and see what it has to offer. The largest window (1) is called
the Command Window. This is where you issue Matlab commands and perform computations.
The top left window (2) is the Workspace, which shows all variables initiated by the user. By
pressing the above tabs, you can also open the Current Directory Window. This will show what
files are in the current directory and allows you to open, rename or delete files. Finally, the
2

Figure 1: The Matlab desktop

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.

3 Creating and Manipulating Vectors


3.1 Creating variables, vectors and arrays
Since it is mainly used for scientific computation, Matlab makes it very easy to create variables.
In fact, Matlab is dynamically typed, meaning you do not have to declare a specific type when
creating variables.
In the command window, you should see >>. You can enter a command at this point. For
example, I will do the following:

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

One can also make vectors of consecutive values easily by inputting

>> 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.

3.2 Operators and functions


Now that we know how to create variables, we can now perform computations on them. In
most common programming languages, one usually has to create mathematical operators from
scratch. For example, a factorial is commonly implemented using a recursive function.
In Matlab , however, a large number of operators are already created for you. They
are usually implemented as functions. Libraries of these functions are called toolboxes and
oftentimes have very specific purposes. Some examples include the Signal Processing Toolbox,
Image Processing Toolbox, and Neural Network Toolbox. Luckily, these toolboxes are simple
to install and use. The Athena machines and student license from IS&T should have almost
everything you would ever need.
To start, you can do basic arithmetic on the console. Try out the following commands:

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

4 Making Plots in Matlab


Besides being great for manipulating data, Matlab is a powerful tool for displaying infor-
mation. Plotting is very easy, but there is also much functionality and configurability in the
environment. A simple example is given:

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

An alternative is to use the hold command:

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

5 Writing Scripts and Functions for Matlab


Although one can use the console to type commands, I find it often helpful to write Matlab
scripts and functions. A Matlab script is simply a set of commands stored in a .m file, which
can be edited in any text editor. Upon calling the script, Matlab reads the commands one
by one until the end of the file. Scripts are very easy to implement and makes it easier to
troubleshoot problems so I recommend getting into a good habit of using them regularly. To
create a script, go to the desired directory and type in edit <scriptname>.m. Click yes on the
prompt and the Matlab editor will open up. You can type any set of commands, separating
each command with a line break.
You can then run your Matlab script by either pressing F5 in the Matlab editor or going
into the console window and running the command <scriptname>.
You can also create functions in the Matlab editor. Again, a function is a set of Matlab
commands that will be run in order. However, one can specify input parameters and/or output
variables in a script. Moreover, unlike a script, the variables used in a function are local and
will not show in the workspace. This is an effective way to black-box code that you might run
many times.
The following exemplifies the formatting needed for a Matlab script:

function out = tempFunc( in1, in2 )


y1 = in1 + in2; % this is a comment
y2 = sin(in1+in2); % this is another comment
y3 = 100 − 30*in2;
out = max([in1 in2 y1 y2 y3]);
end

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.

6 Some Helpful Matlab Notes


1. There are several Matlab commands to clean the environment.

clc erases the command window.


clear all deletes all the variables in the workspace
close all closes all open figures

2. Some useful constants are easily accessible in Matlab , including

both j and i can be used to indicate imaginary numbers (i.e. 5*j)


pi is a preset variable
the mathematical constant en can be found using the command exp(n)
3. One can also perform logical operations, giving binary outputs. This can be useful in
many cases so it is worth trying out. An example is

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.

7 One Big Example


Let’s try and tie everything together by considering an example in image processing. Imagine
we want to create a function that takes in an image, converts it to grayscale and outputs a
binary image (only black or white) that is set by some user-specified threshold. This is rather
trivial, but allows us to consider some of the skills we have learned. Begin by designating the
current directory to something that is stable and that you have access to. Download a picture
(hopefully not too big) into that directory. Now let’s create a function that performs the desired
task. To begin, create a function. Do so by entering the command edit setThres.m. In the
Matlab Editor, type the following:

function setThres (im, thres)

A = imread(im); % imread reads the image and finds the RGB


% values, putting it into the 3D array A
BW = rgb2gray(A); % change from rgb to grayscale
figure(1)
imshow(BW); % take a look at the grayscale image

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

Now in the command window, type in following command

setThres ('<filename>', <thres>)


where <filename> is the image you downloaded and <thres> is a value from 0 to 255. You
should see two figures and a new jpg image with the output image. Be sure to include the single
quotation marks around the filename to make it into a string.

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.

You might also like