Howard Matlab Basics
Howard Matlab Basics
8 Basics
P. Howard
Fall 2009
Contents
1 Introduction 3
1.1 The Origin of MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Starting MATLAB at Texas A&M University . . . . . . . . . . . . . . . . . 3
1.2.1 MATLAB in a calclab room . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 MATLAB in an Open Access Computer Lab . . . . . . . . . . . . . . 3
1.3 The MATLAB Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Basic Computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6 Diary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Clearing and Saving the Command Window . . . . . . . . . . . . . . . . . . 6
1.8 The Command History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.9 File Management from MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 6
1.10 Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1
3 Plots and Graphs in MATLAB 17
3.1 Plotting Functions with the plot command . . . . . . . . . . . . . . . . . . . 18
3.2 Parametric Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3 Juxtaposing One Plot On Top of Another . . . . . . . . . . . . . . . . . . . 20
3.4 Multiple Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.5 Ezplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.6 Saving Plots as Encapsulated Postscript Files . . . . . . . . . . . . . . . . . 25
3.7 More on Basic Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7 Matrices 44
8 Programming in MATLAB 47
8.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.2.1 The For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.2.2 The While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
8.3 Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
8.3.1 If-Else Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
8.3.2 Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
8.4 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
8.4.1 Parsing Input and Output . . . . . . . . . . . . . . . . . . . . . . . . 49
8.4.2 Screen Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
8.4.3 Screen Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
8.4.4 Screen Input on a Figure . . . . . . . . . . . . . . . . . . . . . . . . . 51
2
9 Miscellaneous Useful Commands 52
11 SIMULINK 52
12 M-book 52
1 Introduction
1.1 The Origin of MATLAB
MATLAB, which stands for MATrix LABoratory, is a software package developed by Math-
Works, Inc. to facillitate numerical computations as well as some symbolic manipulation.
The collection of programs (primarily in Fortran) that eventually became MATLAB were
developed in the late 1970s by Cleve Moler, who used them in a numerical analysis course
he was teaching at the University of New Mexico. Jack Little and Steve Bangert later
reprogrammed these routines in C, and added M-files, toolboxes, and more powerful graph-
ics (original versions created plots by printing asterisks on the screen). Moler, Little, and
Bangert founded MathWorks in California in 1984
3
1.3 The MATLAB Interface
The (default) MATLAB screen is divided into four windows, with a large Command Window
in the middle, a Current Directory window on the left, and two smaller windows (Workspace
and Command History) stacked one atop the other on the right. The Command Window
is where calculations are carried out in MATLAB, while the smaller windows display infor-
mation about your current MATLAB session, your previous MATLAB sessions, and your
computer account. The Command History displays the commands you’ve typed in from
both the current and previous sessions; the Current Directory shows which directory you’re
currently in and what files are in that directory, and the Workspace window displays infor-
mation about each variable defined in your current session. You can choose which of these
options you would like to have displayed by selecting Desktop from the main MATLAB
window and left-clicking on the option. (MATLAB will place a black check to the left of this
option.) Occasionally, it will be important that you are working in a certain directory. You
can change MATLAB’s working directory by double-clicking on a directory in the Current
Directory window. In order to go backwards a directory, click on the folder with a black
arrow on it in the top left corner of the Current Directory window.
>>t=4;
>>s=sin(t)
MATLAB will report that s = -.7568. (Notice that MATLAB assumes that t is in radians,
not degrees.) Next, type the up arrow key on your keyboard, and notice that the command
s=sin(t) comes back up on your screen. Hit the up arrow key again and t=4; will appear
at the prompt. Using the down arrow, you can scroll back the other way, giving you a
convenient way to bring up old commands without retyping them. (The left and right arrow
keys will move the cursor left and right along the current line.)
Occasionally, you will find that an expression you are typing is getting inconveniently
long and needs to be continued to the next line. You can accomplish this by putting in three
dots and typing Enter. Try the following:1
>>2+3+4+...
+5+6
ans =
20
1
In the MATLAB examples of these notes, you can separate the commands I’ve typed in from MATLAB’s
responses by picking out those lines that begin with the command line prompt, >>.
4
Notice that 2+3+4+... was typed at the Command Window prompt, followed by Enter.
When you do this, MATLAB will proceed to the next line, but it will not offer a new prompt.
This means that it is waiting for you to finish the line you’re working on.
>>t=5;
>>v=1:25;
>>s=’howdy’
>>y=solve(’a*y=b’)
>>diary script1.txt
>>x=1
x=
1
>>atan(1)
ans =
0.7854
>>diary off
In this script, the command diary script1.txt creates the file script1.txt, and MATLAB begins
recording the commands that follow, along with MATLAB’s responses. When the command
diary off is typed, MATLAB writes the commands and responses to the file script1.txt.
Commands typed after the diary off command will no longer be recorded, but the file
script1.txt can be reopened either with the command diary on or with diary script1.txt.
Finally, the diary file script1.txt can be deleted with the command delete script1.txt.
5
In order to print script1.txt, follow the xprint instructions posted in the Blocker lab.
More precisely, open a terminal window by selecting the terminal icon from the bottom of
your screen and use the xprint command
You will be prompted to give your NetID (neo account ID) and password. The file will be
printed in Blocker 130. △
6
quickly, you can stop it with the command more on. Finally, MATLAB has a nice help
browser that can be invoked by typing helpdesk.
Let’s get some practice with MATLAB help by computing the inverse sine of -.7568.
First, we need to look up MATLAB’s expression for inverse sine. At the prompt, type
helpdesk. Next, in the left-hand window of the pop-up menu, click on the index tab (second
from left), and in the data box type inverse. In the box below your input, you should now
see a list of inverse subtopics. Using your mouse, scroll down to sine and click on it. An
example should appear in the right window, showing you that MATLAB uses the function
asin() as its inverse for sine. Close help (by clicking on the upper right X as usual), and
at the prompt type asin(-.7568). The answer should be -.8584. (Pop quiz: If asin() is the
inverse of sin(), why isn’t the answer 4?)
7
2 Symbolic Calculations in MATLAB
Though MATLAB has not been designed with symbolic calculations in mind, it can carry
them out with the Symbolic Math Toolbox, which is standard with student versions. (In
order to check if this, or any other toolbox is on a particular version of MATLAB, type ver at
the MATLAB prompt.) In carrying out these calculations, MATLAB uses Maple software,
but the user interface is significantly different.
Example 2.1. Suppose we would like to symbolically define the logistic model
N
R(N) = aN(1 − ),
K
where N denotes the number of individuals in a population and R denotes the growth rate
of the population. First, we define both the variables and the parameters as symbolic
objects, and then we write the equation with standard MATLAB operations:
>>syms N R a K
>>R=a*N*(1-N/K)
R=
a*N*(1-N/K)
Here, the expressions preceded by >> have been typed at the command prompt and the
others have been returned by MATLAB. △
Symbolic objects can also be defined to take on particular numeric values.
Example 2.2. Suppose that we want a general form for the logistic model, but we know
that the carrying capacity K is 10, and we want to specify this. We can use the following
commands:
>>K=sym(10)
K=
10
>>R=a*N*(1-N/K)
R=
a*N*(1-1/10*N)
8
2.1.1 Complex Numbers
You can also define and manipulate symbolic complex numbers in MATLAB.
Example 2.3. Suppose we would like to define the complex number z = x + iy and
compute z 2 and zz̄. We use
>>syms x y real
>>z=x+i*y
z=
x+i*y
>>square=expand(zˆ2)
square =
xˆ2+2*i*x*y-yˆ2
>>zzbar=expand(z*conj(z))
zzbar =
xˆ2+yˆ2
Here, we have particularly specified that x and y be real, as is consistent with complex
notation. The built-in MATLAB command conj computes the complex conjugate of its
input, and the expand command is required in order to force MATLAB to multiply out the
expressions. (The expand command is discussed more below in Subsubsection 2.2.2.)
by powers of x. We use
9
>>syms x
>>f=x*(sin(x)+xˆ3)*(exp(x)+xˆ2)
f=
x*(sin(x)+xˆ3)*(exp(x)+xˆ2)
>>collect(f)
ans =
xˆ6+exp(x)*xˆ4+sin(x)*xˆ3+sin(x)*exp(x)*x
△
10
2.2.4 The Horner Command
The horner command is useful in preparing an expression for repeated numerical evaluation.
In particular, it puts the expression in a form that requires the least number of arithmetic
operations to evaluate.
>>syms x
>>f=xˆ4-2*xˆ2+1
f=
xˆ4-2*xˆ2+1
>>horner(f)
ans =
1+(-2+xˆ2)*xˆ2
Example 2.8. Suppose we would like a reduced expression for the function
1 1
f (x) = (1 + + 2 )(1 + x + x2 ).
x x
We use
>>syms x f
>>f=(1+1/x+1/xˆ2)*(1+x+xˆ2)
f=
(1+1/x+1/xˆ2)*(x+1+xˆ2)
>>simple(f)
simplify:
(x+1+xˆ2)ˆ2/xˆ2
radsimp:
(x+1+xˆ2)ˆ2/xˆ2
combine(trig):
(3*xˆ2+2*x+2*xˆ3+1+xˆ4)/xˆ2
factor:
(x+1+xˆ2)ˆ2/xˆ2
expand:
2*x+3+xˆ2+2/x+1/xˆ2
combine:
(1+1/x+1/xˆ2)*(x+1+xˆ2)
11
convert(exp):
(1+1/x+1/xˆ2)*(x+1+xˆ2)
convert(sincos):
(1+1/x+1/xˆ2)*(x+1+xˆ2)
convert(tan):
(1+1/x+1/xˆ2)*(x+1+xˆ2)
collect(x):
2*x+3+xˆ2+2/x+1/xˆ2
mwcos2sin:
(1+1/x+1/xˆ2)*(x+1+xˆ2)
ans =
(x+1+xˆ2)ˆ2/xˆ2
In this example, three lines have been typed, and the rest is MATLAB output as it tries
various possibilities. In returns the expression in ans, in this case from the factor command.
△
Example 2.9. Suppose we would like to re-write the expression from Example 3.8 in a
more readable format. Assuming, we have already defined f as in Example 3.8, we use
pretty(f ) at the MATLAB prompt. (The output of this command doesn’t translate well
into a printed document, so I won’t give it here.)
ax2 + bx + c = 0.
We use
>>syms a b c x
>>eqn=a*xˆ2+b*x+c
eqn =
a*xˆ2+b*x+c
>>roots=solve(eqn)
roots =
1/2/a*(-b+(bˆ2-4*a*c)ˆ(1/2))
1/2/a*(-b-(bˆ2-4*a*c)ˆ(1/2))
12
Observe that we only defined the expression on the left-hand side of our equality. By default,
MATLAB’s solve command sets this expression to 0. Also, notice that MATLAB knew which
variable to solve for. (It takes x as a default variable.) Suppose that in lieu of solving for x,
we know x and would like to solve for a. We can specify this with the following commands:
>>a=solve(eqn,a)
a=
-(b*x+c)/xˆ2
In this case, we have particularly specified in the solve command that we are solving for a.
Alternatively, we can type an entire equation directly into the solve command. For example:
>>syms a
>>roots=solve(a*xˆ2+b*x+c)
roots =
1/2/a*(-b+(bˆ2-4*a*c)ˆ(1/2))
1/2/a*(-b-(bˆ2-4*a*c)ˆ(1/2))
Here, the syms command has been used again because a has been redefined in the code
above. Finally, we need not first make our variables symbolic if we put the expression in
solve in single quotes. We could simply use solve(’a*xˆ2+b*x+c’). △
MATLAB’s solve command can also solve systems of equations.
Example 2.11. For a population of prey x with growth rate Rx and a population of
predators y with growth rate Ry , the the Lotka–Volterra predator–prey model is
Rx = ax − bxy
Ry = − cy + dxy.
In this example, we would like to determine whether or not there is a pair of population
values (x, y) for which neither population is either growing or decaying (the rates are both
0). We call such a point an equilibrium point. The equations we need to solve are:
0 = ax − bxy
0 = − cy + dxy.
In MATLAB
>>syms a b c d x y
>>Rx=a*x-b*x*y
Rx =
a*x-b*x*y
>>Ry=-c*y+d*x*y
Ry =
-c*y+d*x*y
>>[prey pred]=solve(Rx,Ry)
13
prey =
0
1/d*c
pred =
0
1/b*a
Again, MATLAB knows to set each of the expression Rx and Ry to 0. In this case, MAT-
LAB has returned two solutions, one with (0, 0) and one with ( dc , ab ). In this example, the
appearance of [prey pred] particularly requests that MATLAB return its solution as a vector
with two components. Alternatively, we have the following:
>>pops=solve(Rx,Ry)
pops =
x: [2x1 sym]
y: [2x1 sym]
>>pops.x
ans =
0
1/d*c
>>pops.y
ans =
0
1/b*a
In this case, MATLAB has returned its solution as a MATLAB structure, which is a data
array that can store a combination of different data types: symbolic variables, numeric
values, strings etc. In order to access the value in a structure, the format is
14
>>syms x
>>r=solve(xˆ3+2*x-1);
>>eval(r)
ans =
0.4534
-0.2267 + 1.4677i
-0.2267 - 1.4677i
>>double(r)
ans =
0.4534
-0.2267 + 1.4677i
-0.2267 - 1.4677i
MATLAB’s symbolic expression for r is long, so I haven’t included it here, but you should
take a look at it by leaving the semicolon off the solve line. △
>>syms a K N
>>R=a*N*(1-N/K)
R=
a*N*(1-N/K)
>>R=subs(R,a,.1)
R=
1/10*N*(1-N/K)
>>R=subs(R,K,10)
R=
1/10*N*(1-1/10*N)
Alternatively, numeric values can be substitued in. We can accomplish the same result as
above with the commands
>>syms a K N
>>R=a*N*(1-N/K)
R=
a*N*(1-N/K)
>>a=.1
15
a=
0.1000
>>K=10
K=
10
>>R=subs(R)
R=
1/10*N*(1-1/10*N)
In this case, the specifications a = .1 and K = 10 have defined a and K as numeric values.
The subs command, however, places them into the symbolic expression.
16
3 Plots and Graphs in MATLAB
The primary tool we will use for plotting in MATLAB is plot().
Example 3.1. Plot the line that passes through the points {(1, 4), (3, 6)}.
We first define the x values (1 for the first point and 3 for the second) as a single variable
x = (1, 3) (typically referred to as a vector ) and the y values as the vector y = (4, 6), and then
we plot these points, connecting them with a line. The following commands (accompanied
by MATLAB’s output) suffice:
>>x=[1 3]
x=
1 3
>>y=[4 6]
y=
4 6
>>plot(x,y)
5.8
5.6
5.4
5.2
4.8
4.6
4.4
4.2
4
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3
In MATLAB it’s particularly easy to decorate a plot. For example, minimize your plot by
clicking on the left button on the upper right corner of your window, then add the following
lines in the Command Window:
The only command here that needs explanation is the last. It simply tells MATLAB to plot
the x-axis from 0 to 4, and the y-axis from 2 to 10. If you now click on the plot’s button at
the bottom of the screen, you will get the labeled figure, Figure 2.
I added the legend after the graph was printed, using the menu options. Notice that all
this labeling can be carried out and edited from these menu options. After experimenting
17
Useless Plot
10
Useless line
8
2
0 0.5 1 1.5 2 2.5 3 3.5 4
Here is a label for the x−axis
a little, your plots will be looking great (or at least better than the default-setting figures
displayed here). Not only can you label and detail your plots, you can write and draw
on them directly from the MATLAB window. One warning: If you retype plot(x,y) after
labeling, MATLAB will think you want to start over and will give you a clear figure with
nothing except the line. To get your labeling back, use the up arrow key to scroll back
through your commands and re-issue them at the command prompt. (Unless you labeled
your plots using menu options, in which case you’re out of luck, though this might be a good
time to consult Section 3.6 on saving plots.) △
Defining vectors as in the example above can be tedious if the vector has many compo-
nents, so MATLAB has a number of ways to shorten your work. For example, you might
try:
>>X=1:9
X=
1 2 3 4 5 6 7 8 9
>>X=0:2:10
X=
0 2 4 6 8 10
>>x=linspace(0,1,20)
x=
18
Columns 1 through 8
0 0.0526 0.1053 0.1579 0.2105 0.2632 0.3158 0.3684
Columns 9 through 16
0.4211 0.4737 0.5263 0.5789 0.6316 0.6842 0.7368 0.7895
Columns 17 through 20
0.8421 0.8947 0.9474 1.0000
>>f=x.ˆ2
f=
Columns 1 through 8
0 0.0028 0.0111 0.0249 0.0443 0.0693 0.0997 0.1357
Columns 9 through 16
0.1773 0.2244 0.2770 0.3352 0.3989 0.4681 0.5429 0.6233
Columns 17 through 20
0.7091 0.8006 0.8975 1.0000
>>plot(x,f)
Only three commands have been typed; MATLAB has done the rest. One thing you should
pay close attention to is the line f=x.ˆ2, where we have used the array operation .ˆ. This
operation .ˆ signifies that the vector x is not to be squared (a dot product, yielding a scalar),
but rather that each component of x is to be squared and the result is to be defined as a
component of f , another vector. Similar commands are .* and ./. These are referred to as
array operations, and you will need to become comfortable with their use. △
Example 3.3. In our section on symbolic algebra, we encountered the logistic population
model, which relates the number of individuals in a population N with the rate of growth
of the population R through the relationship
N a
R(N) = aN(1 − ) = − N 2 + aN.
K K
Taking a = 1 and K = 10, we have
R(N) = −.1N 2 + N.
In order to plot this for populations between 0 and 20, we use the following MATLAB code,
which creates Figure 3.
>>N=linspace(0,20,1000);
>>R=-.1*N.ˆ2+N;
>>plot(N,R)
Observe that the rate of growth is positive until the population achieves its “carrying capac-
ity” of K = 10 and is negative for all populations beyond this. In this way, if the population
is initially below its carrying capacity, then it will increase toward its carrying capacity, but
will never exceed it. If the population is initially above the carrying capacity, it will decrease
toward the carrying capacity. The carrying capacity is interpreted as the maximum number
of individuals the environment can sustain. △
19
5
−5
−10
−15
−20
0 2 4 6 8 10 12 14 16 18 20
>>t=linspace(-1,1,100);
>>x=t.ˆ2 + 1;
>>y=exp(t);
>>plot(x,y)
>>plot(t,x,t,y);
20
3
2.5
1.5
0.5
0
1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2
The color and style of the graphs can be specified in single quotes directly after the pair of
values. For example, if we would like the plot of x(t) to be red, and the plot of y(t) to be
green and dashed, we would use
>>plot(t,x,’r’,t,y,’g–’)
>>plot(t,x)2
>>hold on
>>plot (t,y)
>>title(’One plot over the other’)
>>u=[-1 0 1];
>>v=[1 0 -1]
>>plot(u,v)
21
Example 3.6. Plot the three functions f (x) = x, g(x) = x2 , and h(x) = x3 .
The following sequence of commands produces the plot given in Figure 5.
>>x = linspace(0,1,20);
>>f = x;
>>g = x.ˆ2;
>>h = x.ˆ3;
>>subplot(3,1,1);
>>plot(x,f);
>>subplot(3,1,2);
>>plot(x,g);
>>subplot(3,1,3);
>>plot(x,h);
0.5
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
0.5
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
0.5
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
The only new command here is subplot(m,n,p). This command creates m rows and n columns
of graphs and places the current figure in position p (counted left to right, top to bottom).
3.5 Ezplot
In most of our plotting for M151, we will use the plot command, but another option is the
built-in function ezplot, which can be used along with symbolic variables.
Example 3.7. Plot the function
f (x) = x4 + 2x3 − 7x2 .
We can use
>>syms f x
>>f=xˆ4+2*xˆ3-7*x
f=
xˆ4+2*xˆ3-7*x
>>ezplot(f)
22
In this case, MATLAB chooses appropriate axes, and we obtain the plot in Figure 6.
x4+2 x3−7 x
1600
1400
1200
1000
800
600
400
200
−6 −4 −2 0 2 4 6
x
We can also specify the domain on which to plot with ezplot(f,xmin,xmax). For example,
ezplot(f,-1,1) creates Figure 7.
Alternatively, the variables need not be defined symbolically if they are placed in single
quotes. We could also plot this example using respectively
>>ezplot(’xˆ4+2*xˆ3-7*x’)
or
>>ezplot(’xˆ4+2*xˆ3-7*x’,-1,1)
△
The ezplot command can also be a good way for plotting implicitly defined relations, by
which we mean relations between x and y than cannot be solved for one variable in terms
of the other.
Example 3.8. Plot y versus x given the relation
x2 y 2
+ = 1.
9 4
This is, of course, the equation of an ellipse, and it can be plotted by separately graphing
each of the two solution curves r
x2
y = ±2 1 − .
9
Alternatively, we can use the following single command to create Figure 8.
23
x4+2 x3−7 x
−2
−4
x2/9+y2/4=1
2
1.5
0.5
0
y
−0.5
−1
−1.5
−2
−3 −2 −1 0 1 2 3
x
x2 y2
Figure 8: The ellipse described by 9
+ 4
= 1.
24
>>ezplot(’xˆ2/9+yˆ2/4=1’,[-3,3],[-2,2])
Here, observe that the first interval specifies the values of x and the second specifies the
values for y. △
Finally, we can use ezplot to plot parametrically defined relations.
Example 3.9. Use ezplot to plot y versus x, given x(t) = t2 +1 and y(t) = et , for t ∈ [−1, 1].
We can accomplish this with the single command
>>ezplot(’tˆ2+1’,’exp(t)’,[-1,1])
25
4 Semilog and Double-log Plots
In many applications, the values of data points can range significantly, and it can become
convenient to work with log10 values of the original data. In such cases, we often work with
semilog or double-log (or log-log) plots.
Year Population
-4000 7 × 106
-2000 2.7 × 107
1 1.7 × 108
2000 6.1 × 109
We can plot these values in MATLAB with the following commands, which produce
Figure 9.
9
x 10
7
0
−4000 −3000 −2000 −1000 0 1000 2000
Looking at Figure 9, we immediately see a problem: the final data point is so large that
the remaining points are effectively zero on the scale of our graph. In order to overcome this
26
problem, we can take a base 10 logarithm of each of the population values. That is,
>>logpops=log10(pops);
>>plot(years,logpops,’o’)
10
9.5
8.5
7.5
6.5
−4000 −3000 −2000 −1000 0 1000 2000
We can improve this slightly with MATLAB’s built-in function semilogy. This function
carries out the same calculation we just did, but MATLAB adds appropriate marks on the
vertical axis to make the scale easier to read. We use
>>semilogy(years,pops,’o’)
The result is shown in Figure 11. Observe that there are precisely eight marks in Figure 11
between 107 and 108 . The first of these marks 2 × 107 , the second 3 × 107 etc. up to the
eighth, which is 9 × 107 . At that point, we have reached the mark for 108 .
27
10
10
9
10
8
10
7
10
6
10
−4000 −3000 −2000 −1000 0 1000 2000
N = f (x),
where N denotes the number of individuals in the population during year x. We proceed by
observing that the four points in Figure 11 all lie fairly close to the same straight line. In
Section ??, we will discuss how calculus can be used to find the exact form for such a line,
but for now we simply allow MATLAB to carry out the computation. From the graphics
window for Figure 10 (the figure created prior to the use of semilogy), choose Tools, Basic
Fitting. From the Basic Fitting menu, choose a Linear fit and check the box next to
Show Equations. This produces Figure 12.
This line suggests that the relationship between N and x is
(Recall that we obtained this figure by taking log10 of our data.) Taking each side of this
last expression as an exponent for the base 10, we find
28
10
data 1
linear
y = 0.00048*x + 8.6
9.5
8.5
7.5
6.5
−4000 −3000 −2000 −1000 0 1000 2000
N S
1 10000
10 316.23
50 28.28
100 10
S = f (N).
We proceed by taking the base 10 logarithm of all the data and creating a double-log plot
of the resulting values. The following MATLAB code produces Figure 13.
>>N=[1 10 50 100];
>>S=[10000 316.23 28.28 10];
>>loglog(N,S)
29
4
10
3
10
2
10
1
10
0 1 2
10 10 10
Figure 13: Double-log plot of average plant size S versus number of plants N.
Since the graph of the data is a straight line in this case,3 we can compute the slope
and intercept from standard formulas. In standard slope-intercept form, we can write the
equation for our line as
log10 S = m log10 N + b.
The slope is
y2 − y1
m= ,
x2 − x1
where (x1 , y1 ) and (x2 , y2 ) denote two points on the line, and b is the value of log10 S when
N = 1 (because log10 1 = 0). In reading the plot, notice that values 10k should be interpreted
simply as k. That is,
4−1 3
m= =− ,
0−2 2
and
b = 4.
We conclude
3
log10 S = − log10 N + 4.
2
In order to get a functional relationship of the type we are interested in, we take each side
of this last expression as an exponent for the base 10. That is,
3 −3 3
10log10 S = 10− 2 log10 N +4 = 10log N 2
104 ⇒ S = 104 N − 2 .
In practice, the multiplication factor 104 varies from situation to situation, but the power
3
law N − 2 is fairly common. We often write
3
S ∝ N−2 .
3
Cooked up, admittedly, though the relationship we’ll get in the end is fairly general.
30
△
31
5 Inline Functions and M-files
Functions can be defined in MATLAB either in line (that is, at the command prompt) or as
M-files (separate text files).
32
>>f=inline(vectorize(’xˆ2’))
f=
Inline function:
f1(x) = x.ˆ2
>>x=[1 2]
x=
1 2
>>f(x)
ans =
1 4
△
Finally, in some cases it is convenient to define an inline function when the variables are
symbolic. Since the inline function expects a string, or character, as input, we first convert
the symbolic expression into a string expression.
Example 5.4. Compute the inverse of the function
1
f (x) = , x > −1,
x+1
and define the result as a MATLAB inline function. Compute f −1 (5).
We use
>>finv=solve(’1/(x+1)=y’)
finv =
-(y-1)/y
>>finv=inline(char(finv))
finv =
Inline function:
finv(y) = -(y-1)/y
>>finv(5)
ans =
-0.8000
Observe that the variable finv is originally defined symbolically even though the expression
MATLAB solves is given as a string. The char command converts finv into a string, which
is appropriate as input for inline. △
Inline functions can be plotted with either the ezplot command or the fplot (function
plot) command.
Example 5.5. Define the function f (x) = x + sin x as an inline function and plot if for
x ∈ [0, 2π] using first the ezplot command and second the fplot command.
The following commands create, respectively, Figure 14 and Figure 15.
>>f=inline(’x+sin(x)’)
f=
Inline function:
33
f(x) = x+sin(x)
>>ezplot(f,[0 2*pi])
>>fplot(f,[0 2*pi])
x+sin(x)
0 1 2 3 4 5 6
x
x = linspace(0,2*pi,50);
f = sin(x);
plot(x,f)
Save this file by choosing File, Save As from the main menu. In this case, save the file as
sineplot.m, and then close or minimize your editor window. Back at the command line, type
sineplot at the prompt, and MATLAB will plot the sine function on the domain [0, 2π]. It
has simply gone through your file line by line and executed each command as it came to it.
34
7
0
0 1 2 3 4 5 6
>>edit sineplot
In MATLAB’s editor, revise your file sineplot.m so that it has the following form:
function sineplot(n)
x = linspace(0,2*pi,n);
f = sin(x);
plot(x,f)
Every function M-file begins with the command function, and the input is always placed in
parentheses after the name of the function M-file. Save this file as before and then run it
with 5 points by typing
>>sineplot(5)
In this case, the plot should be fairly poor, so try it with 50 points (i.e., use sineplot(50)).
We can also take several inputs into our function at once. As an example, suppose that
we want to take the left and right endpoints of our plotting interval as input (as well as the
number of points). We use
35
function sineplot(a,b,n)
x = linspace(a,b,n);
f = sin(x);
plot(x,f)
Here, observe that order is important, so when you call the function you will need to put
your inputs in the same order as they are read by the M-file. For example, to again plot sine
on [0, 2π], we use
>>sineplot(0,2*pi,50).
MATLAB can also take multiple inputs as a vector. Suppose the three values 0, 2π, and 50
are stored in the vector v. That is, in MATLAB you have typed
>>v=[0,2*pi,50];
In this case, we write a function M-file that takes v as input and appropriately places its
components.
function sineplot(v)
x = linspace(v(1),v(2),v(3));
f = sin(x);
plot(x,f)
In this new version, we have made two important changes. First, we have added maxvalue =
to our first line, specifying that the value we want MATLAB to return is the one we compute
as maxvalue. Second, we have added a line to the code that computes the maximum of f
and assigns its value to the variable maxvalue. (The MATLAB function max takes vector
input and returns the largest component.) When running an M-file that returns data from
the command window, you will typically want to assign the returned value a designation.
Here, you might use
>>m=sineplot(v)
36
The maximum of sin(x) on this interval will be recorded as the value of m.
MATLAB can also return multiple values. Suppose we would like to return both the
maximum and the minimum of f in this example. We use
>>[m,n]=sineplot(v)
The value of m will now be the minimum of sin(x) on this interval, while n will be the
maximum.
As our last example, we will write a function M-file that takes vector input and returns
vector output. In this case, the input will be as before, and we will record the minimum and
maximum of f in a vector. We have
function w = sineplot(v)
x = linspace(v(1),v(2),v(3));
f = sin(x);
w = [min(f),max(f)];
plot(x,f)
>>b=sineplot(v)
5.5 Subfunctions
Function M-files can have subfunctions (script M-files cannot have subfunctions). In the
following example, the subfunction subfun simply squares the input x.
For more information about script and function M-files, see Section 6 of these notes, on
Programming in MATLAB.
37
5.6 Debugging M-files
Since MATLAB views M-files as computer programs, it offers a handful of tools for debug-
ging. First, from the M-file edit window, an M-file can be saved and run by clicking on the
icon with the white sheet and downward-directed blue arrow (alternatively, choose Debug,
Run or simply type F5). By setting your cursor on a line and clicking on the icon with the
white sheet and the red dot, you can set a marker at which MATLAB’s execution will stop.
A green arrow will appear, marking the point where MATLAB’s execution has paused. At
this point, you can step through the rest of your M-file one line at a time by choosing the
Step icon (alternatively Debug, Step or F6).
Unless you’re a phenomenal programmer, you will occasionally write a MATLAB program
(M-file) that has no intention of stopping any time in the near future. You can always abort
your program by typing Control-c, though you must be in the MATLAB Command Window
for MATLAB to pay any attention to this. If all else fails, Control-Alt-Backspace will
end your session on a calclab account.
38
6 Basic Calculus in MATLAB
Of course, MATLAB comes equipped with a number of tools for evaluating basic calculus
expressions.
6.1 Differentiation
Symbolic derivatives can be computed with diff(). To compute the derivative of x3 , type:
>>syms x;
>>diff(xˆ3)
ans =
3*xˆ2
>>f=inline(’xˆ3’,’x’);
>>diff(f(x))
ans =
3*xˆ2
Higher order derivatives can be computed simply by putting the order of differentiation after
the function, separated by a comma.
>>diff(f(x),2)
ans =
6*x
Finally, MATLAB can compute partial derivatives. See if you can make sense of the following
input and output.
>>syms y;
>>g=inline(’xˆ2*yˆ2’,’x’,’y’)
g=
Inline function:
g(x,y) = xˆ2*yˆ2
>>diff(g(x,y),y)
ans =
2*xˆ2*y
39
6.2 Integration
Symbolic integration is similar to symbolic differentiation. To integrate x2 , use
>>syms x;
>>int(xˆ2)
ans =
1/3*xˆ3
or
>>f=inline(’xˆ2’,’x’)
f=
Inline function:
f(x) = xˆ2
>>int(f(x))
ans =
1/3*xˆ3
R1
The integration with limits 0
x2 dx can easily be computed if f is defined inline as above:
>>int(f(x),0,1)
ans =
1/3
R π R sin x
For double integrals, such as 0 0
(x2 + y 2 )dydx, simply put one int() inside another:
>>syms y
>>int(int(xˆ2 + yˆ2,y,0,sin(x)),0,pi)
ans =
piˆ2-32/9
Numerical integration is accomplished through the commands quad , quadv, and quadl . For
example,
quadl(vectorize(’exp(-xˆ4)’),0,1)
ans =
0.8448
(If x has been defined as a symbolic variable, you don’t need the single quotes.) You might
also experiment with the numerical double integration function dblquad . Notice that the
function to be numerically integrated must be a vector; hence, the vectorize command. In
particular, the vectorize command changes all operations in an expression into array oper-
ations. For more information on vectorize, type help vectorize at the MATLAB Command
Window.
40
6.3 Limits
MATLAB can also compute limits, such as
sin x
lim = 1.
x→0 x
We have,
>>syms x;
>>limit(sin(x)/x,x,0)
ans =
1
>>limit(abs(x)/x,x,0,’left’)
ans =
-1
>>limit(abs(x)/x,x,0,’right’)
ans =
1
x4 + x2 − 3 1
lim 4
= ,
x→∞ 3x − log x 3
we can type
41
>>X=1:7
X=
1 2 3 4 5 6 7
>>sum(X)
ans =
28
Similarly, for the product
7
Y
n = 1 · 2 · 3 · 4 · 5 · 6 · 7 = 5040,
n=1
we have
>>prod(X)
ans =
5040
MATLAB is also equipped for evaluating sums symbolically. Suppose we want to evaluate
n
X 1 1 1
( − )=1− .
k k+1 n+1
k=1
We type
>>syms k n;
>>symsum(1/k - 1/(k+1),1,n)
ans =
-1/(n+1)+1
42
6.6 Maximization and Minimization
MATLAB has several built in tools for maximization and minimization. One of the most
direct ways to find the maximum or minimum value of a function is directly from a MATLAB
plot. In order to see how this works, create a simple plot of the function f (x) = sin x − π2 x
for x ∈ [0, π2 ]:
>>x=linspace(0,pi/2,25);
>>f=sin(x)-(2/pi)*x;
>>plot(x,f)
Now, in the graphics menu, choose Tools, Zoom In. Use the mouse to draw a box around
the peak of the curve, and MATLAB will automatically redraw a refined plot. By refining
carefully enough (and choosing a sufficient number of points in our linspace command), we
can determine a fairly accurate approximation of the function’s maximum value and of the
point at which it is achieved.
In general, we will want a method more automated than manually zooming in on our
solution. MATLAB has a number of built-in minimizers: fminbnd(), fminunc(), and fmin-
search(). For straightfoward examples of each of these, use MATLAB’s built-in help. For
a more complicated example of fminsearch(), see Example 2.7 of our course notes Modeling
Basics. In either case, we first need to study MATLAB M-files, so we will consider that
topic next.
43
7 Matrices
We can’t have a tutorial about a MATrix LABoratory without making at least a few com-
ments about matrices. We have already seen how to define two matrices, the scalar, or 1 × 1
matrix, and the row or 1 × n matrix (a row vector, as in Section 4.1). A column vector or
matrix can be defined similarly by
>>x=[1; 2; 3]
This use of semicolons to end lines in matrices is standard, as we see from the following
MATLAB input and output.
>>A=[1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
>>A(2,2)
ans =
5
>>det(A)
ans =
0
>>B=[1 2 2; 1 1 2; 0 3 3]
B=
1 2 2
1 1 2
0 3 3
>>det(B)
ans =
-3
>>Bˆ(-1)
ans =
1.0000 -0.0000 -0.6667
1.0000 -1.0000 0
-1.0000 1.0000 0.3333
>>A*B
ans =
3 13 15
9 31 36
15 49 57
>>A.*B
ans =
1 4 6
4 5 12
0 24 27
44
Note in particular the difference between A ∗ B and A. ∗ B.
A convention that we will find useful while solving ordinary differential equations numer-
ically is the manner in which MATLAB refers to the column or row of a matrix. With A still
defined as above, A(m, n) represents the element of A in the mth row and nth column. If we
want to refer to the first row of A as a row vector, we use A(1, :), where the colon represents
that all columns are used. Similarly, we would refer to the second column of A as A(:, 2).
Some examples follow.
>>A(1,2)
ans =
2
>>A(2,1)
ans =
4
>>A(1,:)
ans =
123
>>A(:,2)
ans =
2
5
8
It’s also possible to refer to a precise collections of rows and columns of a matrix. For
example, suppose we would like to refer to the matrix created by taking only elements that
are in the first two rows of A and in the first and third columns. That is, we want
1 3
B= .
4 6
In MATLAB, we use
>>B=A([1,2],[1,3])
B=
13
46
Here, we have simply used one vector to designate which rows to select and a second vector
to designate which columns to select.
Finally, adding a prime (’) to any vector or matrix definition transposes it (switches its
rows and columns).
>>A’
ans =
147
258
45
369
>>X=[1 2 3]
X=
123
>>Y=X’
Y=
1
2
3
46
8 Programming in MATLAB
8.1 Overview
Perhaps the most useful thing about MATLAB is that it provides an extraordinarily con-
venient platform for writing your own programs. Every time you create an M-file you are
writing a computer program using the MATLAB programming language. If you are familiar
with C or C++, you will find programming in MATLAB very similar.6 And if you are famil-
iar with any programming language—Fortran, Pascal, Basic, even antiques like Cobol—you
shouldn’t have much trouble catching on. In this section, I will run through the basic com-
mands you will need to get started in programming. Some of these you have already seen in
one form or another on previous pages.
8.2 Loops
8.2.1 The For Loop
One of the simplest and most fundamental structures is the for -loop, exemplified by the
MATLAB code,
f=1;
for n=2:5
f=f*n
end
f=
2
f=
6
f=
24
f=
120
Notice that I’ve dropped off the command prompt arrows, because typically this kind of
structure is typed into an M-file, not in the Command Window. I should point out, however,
that you can type a for-loop directly into the command line. What happens is that after
you type for n=2:5, MATLAB drops the prompt and lets you close the loop with end before
responding. By the way, if you try typing this series of commands in MATLAB’s default
editor, it will space things for you to separate them and make the code easier to read.
One final thing you should know about for is that if you want to increment your index by
something other than 1, you need only type, for example, for k=4:2:50, which counts from
4 (the first number) to 50 (the last number) by increments of 2.
6
In fact, it’s possible to incorporate C or C++ programs into your MATLAB document.
47
8.2.2 The While Loop
One problem with for-loops is that they generally run a predetermined set of times. While-
loops, on the other hand, run until some criterion is no longer met. We might have
x=1;
while x<3
x=x+1
if x > 100
break
end
end
The output for this loop is given below.
x=
2
x=
3
Since while-loops don’t necessarily stop after a certain number of iterations, they are notori-
ous for getting caught in infinite loops. In the example above I’ve stuck a break command in
the loop, so that if I’ve done something wrong and x gets too large, the loop will be broken.
8.3 Branching
Typically, we want a program to run down different paths for different cases. We refer to
this as branching.
48
8.3.2 Switch Statements
A second branching statement in MATLAB is the switch statement. Switch takes a variable—
x in the case of the example below—and carries out a series of calculations depending on
what that variable is. In this example, if x is 7, the variable y is set to 1, while if x is 10 or
17, then y is set to 2 or 3 respectively.
switch x
case 7
y = 1;
case 10
y = 2;
case 17
y = 3;
end
function s=addthree(x, y, z)
%ADDTHREE: Example for nargin and nargout
if nargin < 2
error(’Need at least two inputs for adding’)
end
if nargin == 2
s=x+y;
else
s = x+y+z;
end
>>addthree(1)
??? Error using ==> addthree
Need at least two inputs for adding
>>addthree(1,2)
ans =
3
49
>>addthree(1,2,3)
ans =
6
function s=addall(varargin)
%ADDALL: Example for nargin and nargout
s=sum([varargin{:}]);
>>addall(1)
ans =
1
>>addall(1,2)
ans =
3
>>addall(1,2,3,4,5)
ans =
15
>>x = 2+2;
>>disp([’The answer is ’ num2str(x) ’.’])
The answer is 4.
In this case, num2str() converts the number x into a string appropriate for printing.
The fprintf function is slightly more complicated, but it gives the user more versatility
in creating output. For example,
In this example, the % designates that a number is to be inserted into the text, and the
decimal 5.2 specifies a field width of 5 and a decimal accuracy of 2. The f designates fixed
point (i.e., standard decimal) notation. Likewise, %i designates that an integer is to be
inserted, and %5.4e designates that a number is to be inserted with field width five (or
larger, if necessary, as here), four decimal places of accuracy, and in exponential notation.
Finally, the combination \n creates a new line following the print-out.
50
8.4.3 Screen Input
Often, you will want the user to enter some type of data into your program. Some useful
commands for this are pause, keyboard , and input. Pause suspends the program until the
user hits a key, while keyboard allows the user to enter MATLAB commands until he or she
types return. As an example, consider the M-file
>>example
Hit any key to continue...
Enter a command. (Type ”return” to return to the script file)
>>3+4
ans =
7
>>return
Are you tired of this yet (yes/no)?yes
function example
%EXAMPLE: Marks a spot on a simple graph
p=[1 2 3];
q=[1 2 3];
plot(p,q);
hold on
disp(’Click on the point where you want to plot an x’)
[x y]=ginput(1); %Gives x and y coordinates to point
plot(x,y,’Xk’)
hold off
51
9 Miscellaneous Useful Commands
In this section I will give a list of some of the more obscure MATLAB commands that I find
particularly useful. As always, you can get more information on each of these commands by
using MATLAB’s help command.
• strcmp(str1,str2) (string compare) Compares the strings str1 and str2 and returns
logical true (1) if the two are identical and logical false (0) otherwise.
• char(input) Converts just about any type of variable input into a string (character
array).
• str2num(str) Converts the string str into a numeric variable. (See also str2double().)
11 SIMULINK
SIMULINK is a MATLAB add-on taylored for visually modeling dynamical systems. To get
started with SIMULINK, choose File, New, Model.
12 M-book
M-book is a MATLAB interface that passes through Microsoft Word, apparently allowing for
nice presentations. Unfortunately, my boycott of anything Microsoft precludes the possibility
of my knowing anything about it.
52
choose Terminal). A window should pop up with a prompt that looks something like:
[username]$. Here, you can issue a number of useful commands, of which I’ll discuss the
most useful (for our purposes). (Commands are listed in bold, filenames and directory names
in italics.)
• cp filename1 filename2 Copies a file named filename1 into a file name filename2
(creating filename2 )
• quota Displays the number of blocks your currently using and your quota. Often,
when your account crashes, it’s because your quota has been exceeded. Typically, the
system will allow you to long into a terminal screen to delete files.
• find . -name \*.tag Finds all files ending .tag, in all directories
• man ls Opens the unix on-line help manual information on the command ls. (Think
of it as typing help ls.) Of course, man works with any other command as well. (Use
q to exit.)
• man -k jitterbug Searches the unix manual for commands involving the keyword
jitterbug. (Oddly, there are no matches, but try, for example, man copy.)
53
Any line in a Unix script file that begins with # is simply a comment and will be ignored.
The command echo is Unix’s version of print. Finally, any command typed in will be carried
out. Here, I’ve used the list command. To run this command, type either simply myhelp if
the Unix command path is set on your current directory or ˜/myhelp if the Unix command
path is not set on your current directory.
References
[P] R. Pratap, Getting Started with MATLAB 5: A Quick Introduction for Scientists
and Engineers, Oxford University Press, 1999.
[UNH] http://spicerack.sr.unh.edu/˜mathadm/tutorial/software/matlab.
[MAT] http://www.mathworks.com
54
Index
;, 4 hold on, 21
==, 48 horner(), 11
=, 48
if-else, 48
asin(), 7 inline function, 5, 32
axis, 17 input, 51
integration, 40
branching, 48
break, 48 keyboard, 51
char(), 52 Limits, 41
character string, 5 linspace, 18
clear, 9 loglog(), 29
collect(), 9 loops, 47
Command History, 6
command window, 6 M-book, 52
complex numbers, 9 M-files
continuing a line, 4 debugging, 38
function, 35
dblquad, 40 script, 34
det(), 44 Matrices, 44
diff(), 39 matrix transpose, 45
differentiation, 39 multiple plots, 21
disp, 50
double(), 14 nargin, 49
nargout, 49
eval(), 14 num2str(), 52
expand(), 10
exporting graphs as .eps files, 25 output, 50
ezplot, 22
parsing, 49
factor(), 10 partial derivatives, 39
floating point, 5 pause, 51
for, 47 plot(), 17
formatting output, 5 plots
fplot, 33 multiple, 20
fprintf, 50 pretty(), 12
products, 41
ginput, 51
graphical user interface, 52 quad, 40
graphs quadl, 40
saving, 25
real, 9
help, 6
helpdesk, 7 saving
55
plots as eps, 25
semilogy(), 27
simple(), 11
SIMULINK, 52
sin(), 4
solve(), 12
str2double(), 52
str2num(), 52
strcat, 52
strcmp(), 52
structure, 14
subs(), 15
sums, 41
switch, 49
symbolic, 5
differentiation, 39
Integration, 40
sums, 42
symbolic objects, 8
symsum, 42
Taylor series, 42
unreal, 9
varargin, 50
vectorize, 40
vectorize(), 32
while, 48
Workspace
save as, 6
Zoom, 43
56