A Beginning MATLAB Tutorial for
the UC Davis Department of Mathematics
by Sarah Williams
updated 9/15/2003
Introduction and Overview
- What is MATLAB?
- Why use MATLAB? Why not?
Command-Line MATLAB
- Launch MATLAB
- Generate matrices
- Implement functions
- Write a small program that generates a plot
M-File MATLAB
- Directory Structure (where will you save your file?)
- Put your small program into an m-file, and run it
- Scripts vs. Functions: write a function m-file
- Get your Scripts and Functions Talking
- Add More Features and Get More Help
Introduction and Overview
Please note that MatLAB can be accessed both on the department computers and from home via SSH. From home, one can even combine SSH with X Windows to use the graphical version of MatLAB.
What is MATLAB?
MATLAB is both a programming language and a software package. "MATLAB"
stands for "Matrix Laboratory." Accordingly, many features exploit
matrices, and assume you are working with matrices. MATLAB
generally solves
problems numerically, not symbolically (compared to Mathematica).
Why use MATLAB? Why not?
Pros:
- It's easy to start using MATLAB, with or without prior programming
experience.
- MATLAB has a lot of built-in mathematical knowledge; e.g.
MATLAB has a function to find the 1-, 2-, or max-norm of a vector -- you
don't have to program this yourself.
- MATLAB has a lot of very powerful "toolboxes" to work in
specific areas of math (optimization, wavelets, etc.)
- It's easy to produce nice graphs.
Cons:
- MATLAB has a lot of "overhead," like graphics and notation that make
it easy to use. This can slow it down compared to more bare-bones programming
languages (like C, FORTRAN). MATLAB may be too slow to solve some
large problems.
- MATLAB is not free - although we have good access at school (and you
can run the school's version remotely), if you happen to want your own private
copy, it costs $100 for students, and more for each toolbox.
Command-Line MATLAB
Launch MATLAB
- Click (once) on the MATLAB icon. (Enter your password
when prompted.)
- OR from the terminal window type "ssh sine" (enter) and then
"matlab"
Generate matrices
- Find the panel called the Command Window. This is where
we will be working.
- Type the following commands:
- In what follows, the >> symbol is meant to represent
the MATLAB prompt (i.e., don't type this yourself).
- Hit the return key at the end of each line; observe the
result and try to understand the cause-and-effect of your commands.
>> A = [1 2 3; 4 5 6]
>> B = [7; 8; 9]
>> C = A*B
- Now try a slightly different version of the same
thing:
>> clear
>> A = [1 2 3; 4 5 6];
(note the semicolon at the end)
>> B = [7 8 9]';
(note the apostrophe)
>> C = A*B;
>> C
>> C'
- Accessing matrix entries (vector components):
>> A
>> A(1,1)
>> A(1,2)
>> A(2,1)
>> B
>> B(1,1)
>> B(1)
>> B(3)
- A very handy way of making uniformly spaced "grids" in MATLAB:
>> clear
>> X = 1:5
>> Y = 3:0.3:5
>> Z = [0:(pi/4):(2*pi)]'
- To review:
- Put square brackets [] around matrices.
- You will get a single row if you just type numbers in the
brackets. To go to the next row, type a semicolon.
- Use * for matrix multiplication (works for regular multiplication,
too).
- MATLAB repeats what you just typed. To suppress this,
put a semicolon ; at the end of the line.
- To see the value of a matrix (or other variable) you've
entered, just type its name and hit return.
- An apostrophe gives you the transpose (the complex conjugate
transpose, in fact) of the matrix.
- To refer to the component of matrix A in the mth row down
and nth column over, type A(m,n). If A is a row or column vector,
you can just type A(j) to see the jth component.
- The colon : notation gives you uniformly spaced grids (row
or column vectors). The first number is the left endpoint of the
grid. If you include a middle number, it's the grid spacing (delta
x); if you don't state a value here, MATLAB assumes you want a value of
1. The last number is the maximum right endpoint of the grid.
- The command "clear" erases all the variable values you've
assigned so you can start fresh. Use this often -- MATLAB has a
bad habit of leaving remnants of old variables lying around unless you explicitly
clear them out.
Implement functions
- Type the following commands:
>> clear
>> c = -pi/2;
>> X = [0:0.1:1]';
>> sin(c)
Now, type the "up" arrow.
MATLAB will display the last thing you typed.
(Type "up" again and you can move backwards through your command
history.) Use the arrow keys
to edit the last line to read:
>> sin(X)
>> sqrt(c)
(Note the imaginary value.)
>> sqrt(abs(c))
>> Y = exp(X)
>> Z = log(Y)
Write a small program that generates a plot
M-File MATLAB
Typing commands directly to MATLAB is well and good, and you will
want to experiment at the command line frequently. However, for
homework assignments and other distinct problems, you will want to keep
your program in a file, so that you can edit it and run it again. You
will also want to make files that call each other -- for example, you could
have a plotting routine that uses the format you like, and each of your
programs could call this routine when it comes time to make a graph.
Directory Structure (where will you save your file?)
Now is the time when we talk about Linux. If you already
know which directory you will save your program files in, skip to the
next section.
- Put MATLAB aside for a moment. (Minimize the window
if you like.)
- Click on the "Localhost" icon to get a new terminal window.
- Initially, you are "sitting" at your "home" directory.
- Type ls to list the subdirectories.
- Do you have a subdirectory where you put your coursework?
Would you like one?
- To create a subdirectory called Courses, type mkdir Courses
(you can change Courses to any other name you prefer)
- Now type cd Courses (cd means change directory)
- Now you are sitting at your Courses directory.
- Type ls to list what's here. Nothing, right? Let's
put something here.
- Type mkdir Math228a to make a directory for numerics.
- Now type ls. Can you see your new folder? This
is a good place to store your MATLAB programs.
- You can exit the terminal window now (type exit) and bring
your MATLAB window back.
Put your small program into an m-file, and run it
- At the top left of the MATLAB window, there is an icon that
looks like a "new document" button. Click (once) on this.
- A blank editor window will open. This is where
you type your program. Type:
(Note: in my experience, trying to copy and paste text into the MATLAB
editor crashes the whole thing. You can try it, but you'll learn
more if you type the text yourself anyway.)
% My Name
% The Date
% The purpose of this program is to plot a semi-circle on [-2,2].
X = -2:0.1:2;
Y = sqrt(4-(X.^2));
plot(X,Y)
- The percent signs % indicate comments. You can put
these anywhere in a program, to explain your code. Use comments
as often as possible; otherwise, you will not remember why you did what
you did.
- Click on the File menu, and choose "Save As."
- You want the top field to contain the right directory (the
one you created in the last step).
- In the bottom field, type the name of the program. Call
it circle1.m
- If your semi-circle figure is still open from before, close
it.
- Click on the command window.
- Take a look at the top of the window. There is a field
labeled "Current Directory." Is it looking in the right place for
your program?
- If not, you can type "cd" and "ls'
in MATLAB just like you can in the terminal window. You might need
to type something like
>> cd Courses/Math228a
- type ls
to see if your program is there. To run your program, type its name, e.g.
>>circle1
Scripts vs. Functions: write a function m-file
- The program you just wrote, circle.m, is called a "script"
- it runs straight from beginning to end, like a script to a play.
- In MATLAB, you can also write a program that is a function.
- A function usually takes input and returns output.
- A function file must start with a "function declaration."
We will see an example below.
- Open a blank program file. Type:
% My Name
% The Date
% The purpose of this program is to plot a semi-circle of a
% given radius.
function Y = circle2(radius)
X = -radius:0.1:radius;
Y = sqrt(radius^2-(X.^2));
plot(X,Y)
- The line function
Y = circle2(radius) is the function declaration. Note:
- The word "function" must be the first (non-comment) word
of the program.
- "Y" is the value that this function returns, or calculates,
a.k.a. the output.
- "radius" is the name of the variable taken as input.
- "circle2" should be both the name of the function and the name
that you use to save the file.
- To run your program for different radii, type:
>>circle2(2)
>>circle2(4);
>>circle2(1);
- Note that the figure is replaced each time you call the function,
and that MATLAB automatically chooses the size of the x- and y-axes.
Get your scripts and functions talking
- Open a blank program file. Type:
% My Name
% The Date
% The purpose of this program is to plot semi-circles
% with radius = 1,2,3, and 4.
for j = 1:4
circle2(j);
end
- Save the file (in the same directory as circle2.m) as makecircles.m
- makecircles.m is a script. It is "calling" circle2.m, which
is a function. They're talking to each other. (Who is saying what?)
- Close any plots that are still open.
- To run the program, type:
>> clear
>> makecircles
- Did you get what you expected? To make the program produce
4 different plots without overwriting, we need to make a small edit:
- Save circle2.m, close any figures that are open, and run makecircles
again.
- A different option: make the program produce one plot showing all
4 circles
- open your circle2.m file
- "comment out" the "figure" line. That
is, put a % in front
of it.
- MATLAB will not read your comments
- "commenting out" can be better than deleting, because you can
easily go back if you change your mind. (by erasing the % mark)
- above plot(X,Y),
add a line that says "hold
on."
- Now your program should read as follows:
% My Name
% The Date
% The purpose of this program is to plot a semi-circle of a
% given radius.
function Y = circle2(radius)
X = -radius:0.1:radius;
Y = sqrt(radius^2-(X.^2));
%figure
hold on
plot(X,Y)
- Save cirlce2.m, close any figures that are open, and run makecircles
again.
- To save your plot:
- At the top of the plot window, click on File
- click on Export
- Verify that it's going in the right directory, give it a name in
place of where it now says *, (try cplot1), and choose a format (eps or color
eps is good)
Add More Features and Get More Help
- Plots should have titles. How do you add a title?
- In the MATLAB window, click on the Help menu item. From the
list that drops down, choose "MATLAB Help."
- You'll get a new window full of help.
- In the left-hand pane, there are 4 tabs: Contents, Index, Search,
and Favorites. Click on Search.
- In the blank box, type "title" (and hit return)
- double-click on the first "hit" -- the one that simply says "title."
- Read the help in the right-hand pane, and see if you can add a line
to your program so that your plot will have a title.
- Maybe you'd rather change the x-axis of your plot, so that it shows
[-5,5].
- Back in the help window, search for "axis"
- double-click on the "hit" that looks the best
- go to it!