You are on page 1of 12

The Basics

Calculator functions work as you'd expect:


>>(1+4)*3

ans =

15

+ and - are addition, / is division, * is multiplication, ^ is an exponent.


You can assign variables from the matlab workspace. Everything in matlab is a matrix. (If it's a
scalar, it's actually a 1x1 matrix, and if it's a vector, it's an Nx1 or 1xN matrix.)
>>a = 3
a =

To create a vector is pretty similar. Each element is separated by spaces, the whole vectore is in
square brackets:
>>v = [1 3 6 8 9]
To create a vector of values going in even steps from one value to another value, you would use
>>b = 1:.5:10
This goes from 1 to 10 in increments of .5. You can use any increment, positive or negative, you
just have to be able to get to the last thing from the first thing, using those increments. If you don't
put in an increment, it assumes it's 1, so 1:5 gives you the vector [1 2 3 4 5].
To turn a row vector into a column vector, just put a ' at the end of it. (This is also how to get the
transpose of a matrix.) To create a matrix, you could do something like:
c = [1 3 6; 2 7 9; 4 3 1]
The semicolons indicate the end of a row. All rows have to be the same length.
Whenever you assign a value in matlab, it will print out the entire value you have just assigned. If
you put a semicolon at the end, it will not print it out, which is much faster.

Dealing with Matrices


Once you have a matrix, you can refer to specific elements in it. Matlab indexes matrices by row
and column. c(3,1) is the element in the third row, 1st column, which is 4. c(2:3,1:2) gives you the
elements in rows 2-3, and columns 1-2, so you get
2 7
4 3

as a result. c(1:3,2) gives you the elements in rows 1-3, and the second column, that is, the entire
second column. You can shortcut this to:
c(:,2)
literally telling matlab to use all the rows in the second column, ie, the 2nd column.
You can get a whole row of a matrix with
c(1,:)
This literally tells matlab to take the first row, all columns.
You can also refer to any matrix with only one index. It will use that index to count down the
columns. c(5) will give you 7, for example.
When you have a matrix or vector (anything with more than one element) you need to do a few
things to make sure all of your math does what you want it to. You can add a constant or multiply
by a constant normally (const+c, const*c, etc.) If you have data in two matrices that correspond (for
example, a time vector and an x position vector that has x values for each point in time), you can
add and subtract those normally (it will map each element properly.)
To multiply, divide, or raise to a power when you have a matrix or vector that is acting as a set of
data points, you need to use
.*
./
.^

so that matlab will multiply each element in the matrix instead of trying to do matrix multiplication
or division.
Of course, it can also treat matrices as actual matrices, so you can solve something like [A]x = b
where A is a matrix of coefficients, x is a column vector of the x values you want to find, and b is
also a column vector just by doing
x = A\b

after you define A and b. The \ represents "left division" (since to solve that equation you would
have to divide both sides by A on the *left* side, since order is significant when dealing with
matrices.).

useful functions
Matlab has a lot of built-in functions. To use a function, just type functionname(arguments) with the
appropriate name and arguments. If you create a time vector t=1:.25:6; you can get standard
functions like
x = sin(t)
which returns a vector the same size as t, with values for the sin of t at all points. You can also do
things like
s = sum(c)
which sums all the columns in a matrix c and returns a row vector of the sums. The function d =
det(c)
takes a matrix c and returns the determinant of it. The matlab booklet has a list of many of these
useful functions.

Help and other tools


Places to get help:
• Typing "help" at the matlab prompt gives you a list of all the possible directories matlab can
find commands in (which also tells you its "search path", or a list of the directories it is
looking in for commands.)
• Typing "help directoryname" gives you a list of the commands in that directory and a short
description of them.
• Typing "help commandname" gives you help on a specific command.
• Typing "lookfor keyword" gives you a list of commands that use that keyword. ie, "lookfor
integral" lists commands that deal with integrals. It's pretty slow, choose the word wisely.
You can use control-c to stop searching when you think you've found what you need.
• Typing "doc" starts up a web browser with the Matlab on Athena home page. This includes
the entire reference manual for matlab, a whole lot of other information on using matlab, and
a pointer to the Matlab Primer, a good introduction to using Matlab.
• You can get copies of "Matlab on Athena" at Graphic Arts. You can also get copies of the
Matlab Primer mentioned above. (There's a small fee for copying costs on both.)
• The matlab manual and manuals for many of the toolboxes are available in some clusters
and can be borrowed from the consultants' office in 11-115.

Some Useful Tools:


• If you accidentally reassign a function name to a variable (ie, you try saying sum = 3 and
then you get errors when you try to use the sum function because it doesn't know it's a
function anymore), you can restore it to its normal state using "clear functionname". You can
also use clear to get rid of all variable values with "clear all".
• who

will tell you all the variables you have currently defined.
• whos

will tell you the variables, their sizes, and some other info.
• pi

is a function of that returns the value of pi.


• eps

is a function that returns Matlab's smallest floating point number. This is useful if you have a
vector that might contain zeros that is going to wind up in the denominator of something. If
you add eps to the vector, you aren't actually adding anything significant, but you won't run
into divide by zero problems anymore.
• format long

and
format short

switch between the long and short display format of numbers. Either way matlab uses the
same number of digits for its calculations, but normally (format short) it will only display
the first four digits after the decimal point.
• Typing
type

functionname for any function in Matlab's search path lets you see how that function is
written.
Plotting
The basic syntax to get a plot in matlab is
plot(x1,y1)
(The x values always come before the y values, x1 and y1 represent variables that your data is
stored in.) If you type a second plot command later, it will clear your first plot. If you type "hold
on" it will hold the current plot so you can add plots on top of one another (until you reset it by
typing "hold off".)
You can plot multiple values with plot(x1,y1,x2,y2) and you can specify the color and linetype of a
plot as something like plot(x1,y1,'w*') to get white *'s for each data point.
To split your plot into a bunch of smaller plots, you can use the subplot command to split it up into
rows and columns.
subplot(r,c,n)
will split the plot window into r rows and c columns of plots and set the current plot to plot number
n of those rows and columns. For example, subplot(2,1,1) splits the plot window into two rows in a
single column and prepares to plot in the top plot. Then your plot command will plot in the top plot.
Then you could switch to the bottom plot with subplot(2,1,2) and use another plot command to plot
in the bottom plot.
You can add titles, labels, and legends to plots.
title('This is a Title')
xlabel('My X axis')
ylabel('My Y axis')
legend('First Thing Plotted','Second Thing Plotted')

legend creates a legend box (movable with the mouse) that automatically uses the right symbols and
colors and sticks the descriptions in the legend command after them.

Printing, Saving, and Loading


Basic printing
>>print -Pprintername
You can also save to a Postscript or Encapsulated Postscript file:
>>print -dps filename.ps
>>prind -deps filename.eps
You can also save your plot as an m-file (matlab script) which should contain all the commands you
need to recreate your plot later. This is about 98 percent accurate.
>>print -dmfile filename.m
You can save and load files as either text data or matlab's own data format. If you have a text file
consisting of a bunch of columns of data separated by spaces or tabs, you can load it into matlab
with
load filename.dat
This command will give you a matrix called filename. Then you can reassign columns of that
matrix, ie
col1 = filename(:,1);
When you save data using the command
save filename.mat
, matlab will save all of your variables and their values in its own format, so that when you load it
using
load filename.mat
you will have all of your variables already defined and names.

Polynomials and Fitting


Matlab can treat a vector as a polynomial. It will assume that the numbers represent the coefficients
of the polynomial going from highest-order to lowest order.
>>p = [1 2 2 4 1]
can represent the polynomial x^4 + 2x^3 + 2x^2 + 4x + 1. There are a number of functions that use
this representation of polynomials:
>>roots(p)
gives you the roots of the polynomail represented by the vector p.
>>polyval(p,4)
gives you the value of the polynomial p when x = 4. Similarly,
>>polyval(p,[1:10])
gives you the value of the polynomial evaluated at each of the points in the vector. (It returns
another vector the same size.)
You can fit polynomials to data sets using this representation and a function called curvefit.
>>[p, fitted] = curvefit(x,y,n)
fits the data in x and y to an nth order polynomial (using 1 gives you a straight line, 2 gives you a
quadratic, etc), and plots both the data and the fitted curve for you. It returns p, the polynomial
representing the equation of the fitted curve, and fitted, the data points you get from the curvefit for
each of the x's in your data set.
You can use polyval and the fitted polynomial p to predict the y value of the data you've fitted for
some other x values.
>>ypred = polyval(p,xvalues)

Logical Conditions and Matrices


Matlab has an interesting way of using logic to choosing elements of matrices. If I have a matrix
a = [ 1 2 3 4 5 6]
and I refer to a(a>3) I will get only the elements of a where a is greater than 3. You can combine
these logical statements. Typing "help ops" will list all of the logical functions and operators you
can use for this.
I can also create a second matrix the same size as a: b = [7 8 9 10 11 12]
and then referring to b(a<3) will give the elements of b which correspond to where a is less than 3
(that is, [7 8]).
The reason this works is because matlab logical functions are designed to return a matrix or vector
of 1's and zeros. If I just typed
>> a>3
I would get [0 0 0 1 1 1] as a result. The first 3 elements are zero, because those elements are not
greater than 3 (F), and the last are 1 because those elements are greater than 3 (T). Then, matlab can
accept matrices like this as a way of specifying indexes for another matrix of the same size. If I just
typed
>> a([0 0 1 0 0 1]),
I would get [3 6] as a result because those are the elements where 1's appear in the vector I gave as
my "index" vector.
This logical indexing capability allows you to do a lot of efficient things with large matrices
because you very rarely have to loop through a whole matrix in order to get only specific parts of it.
Example: You have a matrix called volt with 50,000 values of voltages over time, and a
corresponding matrix called t. To find the mean voltage between time 20 and time 30, you can use
>>mean(volt(t>20 & t<30))
to get the result.

Writing Functions and Scripts


All matlab functions and scripts are plain text files that contain matlab commands. Matlab will treat
any file that ends in .m as either a function or a script. It can find .m files you've written that are in
your ~/matlab directory, in the directory you have cd'd into from the matlab prompt, or in a
directory you've started matlab with (ie,
matlab /mit/2.670/Computers/Matlab/Examples

starts up matlab and adds that directory to the places matlab will look for .m files in.)

Scripts
A script is just a list of commands to be run in some order. Placing these commands in a file that
ends in .m allows you to "run" the script by typing its name at the command line. You type the name
of the script without the .m at the end.

Functions
A function is capable of taking particular variables (called arguments) and doing something specific
to "return" some particular type of result. A function needs to start with the line
function return-values = functionname(arguments)
so that matlab will recognize it as a function. Each function needs to have its own file, and the file
has to have the same name as the function. If the first line of the function is
function answer = myfun(arg1,arg2)
answer = (arg1+arg2)./arg1

then the file must be named myfun.m. The function has arg1 and arg2 to work with inside the
function (plus anything else you want to define inside it, and possibly some global variables as
well), and by the end of the function, anything that is supposed to be returned should have a value
assigned to it. This particular function is just one line long, and it returns answer, which is defined
in terms of the two arguments arg1 and arg2.

Some useful tools for functions and scripts


• nargin

used within a function tells you how many arguments the function was called with.
You can write functions that can accept different numbers of arguments and decide what to
do based on whether it gets two arguments or three arguments, for example.
• eval

lets you take a string and run it as a matlab command.


For example, if I have to plot 20 similar data files for trials and I want to load each file and
use the filename in the title, I can write a function that takes the filename as a string as an
argument. To load it in the function, I can use
str = ['load ' filename]
to put together a command string, and
eval(str)
to run that command.
Then to use the filename in the title, I can use
str = ['title(' filename ')']
eval(str)
• feval

evaluates a function for a given set of arguments. For example, feval('sin',[0:pi/4:2*pi]) is


the same thing as saying sin([0:pi/4:2*pi]). If you're dealing with a situation where you
might want to specify which function to use as an argument to another function, you might
use feval.

Global Variables
When you define a variable at the matlab prompt, it is defined inside of matlab's "workspace."
Running a script does not affect this, since a script is just a collection of commands, and they're
actually run from the same workspace. If you define a variable in a script, it will stay defined in the
workspace.
Functions, on the other hand, do not share the same workspace. A function won't know what a
variable is unless the it gets the variable as an argument, or unless the variable is defined as a
variable that is shared by the function and the matlab workspace, or a global variable.
To use a global variable, every place (function, script, or at the matlab prompt) that needs to share
that variable must have a line near the top identifying it as a global variable, ie:
global phi;

Then when the variable is assigned a value in one of those places, it will have a value in all the
places that begin with the global statement.
Loops and Control
Sometimes, you do need to use some kind of loop to do what you need, rather than just operating on
an entire matrix or vector at once.

While Loops
The syntax for a while loop is
while (some logical expression)
do something;
do something else;
end

To keep this from going on forever, you should probably be changing some variable in the logical
expression within the body of the loop so that it eventually is not true.

For
The syntax for a for loop is:
FOR X = 1:N,
A(X) = 1/(2+X-1);
END

You should try to avoid using i and j as counters, since you will wind up redefining i (which is
intially defined as the imaginary i.)

If
The syntax for an if statement is
if (logical expression)
matlab command
elseif (other logical expression)
another matlab command
else
a matlab command
end

(You don't need an elseif or an else, but you do need an end.)

break
The break command breaks you out of the innermost for or while loop you are in.
In the process of a loop, if you define an element of an vector that doesn't exist yet (the vector is
smaller than the element you're trying to assign), matlab will increase the size of the vector or
matrix to allow for the new element to go where you've specified. However, if you know that you're
going to be assigning elements until the matrix grows to be some specific size, it's better to
"preallocate" the matrix by defining it to be all zeros initially.
matrix = zeros(rows,columns);

will do that.
Examples of some loops are in the file fors.m in the 2.670 Examples directory. (
type fors.m

Debugging Functions
Matlab has an extensive debugger that allows you to examine what is going on inside a function
when you encounter problems with it. If you type "help debug" at the matlab prompt, it will list all
of the debugging commands available.
Debugging commands.

dbstop - Set breakpoint.


dbclear - Remove breakpoint.
dbcont - Resume execution.
dbdown - Change local workspace context.
dbstack - List who called whom.
dbstatus - List all breakpoints.
dbstep - Execute one or more lines.
dbtype - List M-file with line numbers.
dbup - Change local workspace context.
dbquit - Quit debug mode.

Normally, you would enter the debugger by setting a breakpoint either at the beginning of your
function (dbstop in functionname) or at the point where an error first occurs (dbstop if error).
help dbstop

lists some other ways to set a debugging stop to enter debug mode. When it "stops" at the
breakpoint, you will be in the debugger. The prompt looks like K>> instead of >>. The debugger
indicates the next line it will run.
When it's printed a line out, it has not yet run that line. It will run that line the next time you type
"dbstep" to step down another line in the function.
Then you can examine the variables in the function, try to determine what might have the wrong
value, do logical tests, and step through the function one line at a time using "dbstep" to see what
the function is doing step-by-step.

Solving Differential Equations


Matlab has two functions, ode23 and ode45, which are capable of numerically solving differential
equations. Both of them use a similar numerical formula, Runge-Kutta, but to a different order of
approximation.
The syntax for actually solving a differential equation with these functions is:
[T,Y] = ode45('yprime',t0,tF,y0);

'yprime' is the name of a function that you write that describes your system of differential equations.
t0 and tf are the initial and final times that you want a solution for, and y0 is a vector of the initial
values of the variables in your system of equations. You get back a vector of times, T, and a matrix
Y that has the values of each variable in your system of equations over the times in the time vector.
Each column of Y is a different variable.
The hardest part of this is actually defining your differential equation so that matlab understands it.
Matlab has a very specific way to define a differential equation, as a function that takes one vector
of variables in the differential equation, plus a time vector, as an argument and returns the derivative
of that vector. The only way that matlab keeps track of which variable is which inside the vector is
the order you choose to use the variables in. You define your differential equations based on that
ordering of variables in the vector, you define your initial conditions in the same order, and the
columns of your answer are also in that order.
If you follow a careful system to write your differential equation function each time you need to
solve a differential equation, it's not too difficult. I'll do an example in this system to explain how it
works. In my example, x and y are functions of t.

The system of differential equations we're trying to solve is The first thing to notice is

that this is not a first order differential equation, because it has an in it. To create a
function that returns a second derivative, one of the variables you give it has to be the first

derivative. So the variables the function needs to start with are , , and

. The function needs to tell matlab how to get from those variables to ,

, and .
The first step is to write the first line of the function. Since x and y are functions of t, and we
eventually want the differential equation to give us x and y, we'll define the function with
function dxy = diffxy(t, xy)

This function is called diffxy. That means it should be in a file called


diffxy.m

. It takes a vector xy (which has all three of the variables we said we had to give matlab to define
our differential equation in it) and a time vector, and gives us the derivative of the three things in the
the xy vector.
The next step is to assign some variables from the xy vector that this function is given. This is when
we decide what order the three things in the xy vector will be in. We could just keep calling them
xy(1), xy(2), and xy(3), but then we might forget which one of them was supposed to represent x,
which one was supposed to represent y, etc. So the first thing we do is rename some variables:
x = xy(1);
xdot = xy(2);
y = xy(3);

Now we can use x, xdot, and y to define the three things that this function has to return---xdot,
xdoubledot, and ydot. This is where we actually refer to the differential equation and implement it.
The first definition is trivial. We need to express xdot (the derivative of x) in terms of the three
variables we're given. xdot is already one of the three variables we're given, so we can use it to start
with:
xdot = xdot;

Then xdoubledot comes from the first equation:


xdoubledot = 3 - ydot + 2*xdot;

Whoops, we don't _have_ a ydot yet. It's not one of the three variables we're given in xy. But the
second equation tells us what ydot is equal to in terms of things we _are_ given in xy. So what we
really want to say is
ydot = 3*x + 2*y + 5;
xdoubledot = 3 - ydot + 2*xdot;

The last thing we want to define is ydot, which is the derivative of y. We just defined it above in
order to get xdoubledot, so we're done.
So dxy, the thing we return, has to contain xdot, xdoubledot, and ydot in order. The final thing we
have to do is combine those values into the vector dxy:
dxy = [xdot; xdoubledot; ydot];

Then we have a finished function that takes t and xy, and returns dxy, which is the derivative of all
the elements in xy. You can follow this approach for any number of differential equations.
The final program, diffxy.m, looks like
function dxy = diffxy(t, xy)
%
%split xy into variables in our equations
%
x = xy(1);
xdot = xy(2);
y = xy(3);
%
% define the derivatives of these variables from equations
%
xdot = xdot;
ydot = 3*x + 2*y + 5;
xdoubledot = 3 - ydot + 2*xdot;
%
%return the derivatives in dxy in the right order
%
dxy = [xdot; xdoubledot; ydot]

To get a solution, we can type


[T, XY] ode45('diffxy',0,10,[0 1 0])

which uses times from 0 to 10 and assumes that the initial value of x is 0, xdot is 1, and ydot is 0,
and gives us a time vector and a three column vector that contains values of x, xdot, and y over that
time vector.

Vectorization
Matlab is written to deal with matrices and vectores. Because of that, it is much more efficient to
solve problems solely by doing math on your vectors or portions of your vectors, rather than by ever
needing to loop through particular elements in your vector and check their values.
You can actually check this out by timing something like taking the sine of a variable for 100
different values of the variable. The logical way to do it in matlab is to create a vector of those 100
different values, and take the sine of that vector. If you do it instead by a for loop from 1 to 100:
b = [some vector of 100 elements]
for n = 1:100,
a(i) = sin(b(i));
end
it will take much longer. Sometimes you can't avoid using loops, but if you write your matlab
scripts cleverly, you can make them much more efficient. Using logical conditions to select parts of
your matrices (as we discussed in Lecture 1) is one way that is easy to take advantage of in
vectorizing your problems.

You might also like