Professional Documents
Culture Documents
ans =
15
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.
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.
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 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.
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.
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
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
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.
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.
'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)
. 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;
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]
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.