Matlab - Crash Course in Matlab - Found - at - (Redsamara - Com) PDF
Matlab - Crash Course in Matlab - Found - at - (Redsamara - Com) PDF
Matlab - Crash Course in Matlab - Found - at - (Redsamara - Com) PDF
c Tobin A. Driscoll
June 2, 2003
The purpose of this document is to give a medium-length introduction to the essentials of
MATLAB and how to use it well. Im aiming for a document thats somewhere between a two-
page introduction for a numerical methods course and the excellent but longer Getting Started and
other user guides found in the online docs. I use it in a week-long boot camp for graduate
students at the University of Delaware in the summer after their rst year of study.
I assume no knowledge of MATLAB at the start, though a working familiarity with basic linear
algebra is pretty important. The rst four sections cover the basics needed to solve even simple
exercises. (There is also a little information about using MATLAB to make graphics for a technical
paper.) The remaining sections go more deeply into issues and capabilities that should at least be
in the consciousness of a person trying to implement a project of more than a hundred lines or so.
The version of MATLAB at this writing is 6.5 (Release 13). Simulink and the optional toolboxes
are not covered.
Please dont redistribute or alter this document without my permission. Im not stingy with
such permission, but I like to have an idea of where my work goes.
1 Introduction
MATLAB is a software package for computation in engineering, science, and applied mathemat-
ics. It offers a powerful programming language, excellent graphics, and a wide range of expert
knowledge. MATLAB is published by and a trademark of The MathWorks, Inc.
The focus in MATLAB is on computation, not mathematics. Hence symbolic expressions and
manipulations are not possible (except through a clever interface to Maple). All results are not
only numerical but inexact, thanks to the rounding errors inherent in computer arithmetic. The
limitation to numerical computation can be seen as a drawback, but it is a source of strength
too: MATLAB generally runs circles around Maple, Mathematica, and the like when it comes to
numerics.
On the other hand, compared to other numerically oriented languages like C++ and FOR-
TRAN, MATLAB is much easier to use and comes with a huge standard library. The only major
unfavorable comparison here is a gap in execution speed. This gap is maybe not as dramatic as
sin
1
_
1
2
_
_
2 1 0 0 0 1
1 2 1 0 0 0
0 1 2 1 0 0
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
0 0 1 2 1 0
0 0 0 1 2 1
1 0 0 0 1 2
_
_
(b) Nowread about toeplitz and use it to build D. (Use the full MATLAB reference from
helpdesk, which has more to say than just help toeplitz.)
(c) Use toeplitz and whatever else you need to build
_
_
1 2 3 4
0 1 2 3
0 0 1 2
0 0 0 1
_
_
_
_
1
1
2
1
3
1
4
1
2
1
1
2
1
3
1
3
1
2
1
1
2
1
4
1
3
1
2
1
_
_
_
_
4 3 2 1
3 2 1 2
2 1 2 3
1 2 3 4
_
_
Do not just enter the elements directlyyour solutions should be just as easy to use if
the matrices were 100 100.
2. Let A be a random 8 8 matrix. Find the maximum values (a) in each column, (b) in each
row, and (c) overall. Also (d) nd the row and column indices of all elements that are larger
than 0.25.
3. A magic square is an n n matrix in which each integer 1, 2, . . . , n
2
appears once and for
which all the row, column, and diagonal sums are identical. MATLAB has a command
magic that returns magic squares. Check its output at a few sizes and use MATLAB to
verify the summation property. (The antidiagonal sum will be the trickiest.)
4. Suppose we represent a standard deck of playing cards by a vector v containing one copy of
each integer from 1 to 52. Show how to shufe v by rearranging its contents in a random
order. (Note: There is one very easy answer to this problemif you look hard enough.)
2 ARRAYS AND MATRICES 19
5. Examine the eigenvalues of the family of matrices
D
N
= N
2
_
_
2 1 0 0 1
1 2 1 0 0
0 1 2 1 0
.
.
.
.
.
.
.
.
.
.
.
.
0 0 1 2 1
1 0 0 1 2
_
_
where D
N
is N N, for several growing values of N; for example, N = 4, 8, 16, 32. (This
is one approximate representation of the second-derivative operator for periodic functions.
The smallest eigenvalues are integer multiples of a simple number.)
6. Use several random instances of an m n matrix A to convince yourself that
A
2
F
=
K
i=1
2
i
,
where K = min{m, n}, {
1
, . . . ,
K
} are the singular values of A, and
F
is the Frobenius
norm (root-mean-square of the elements of A).
3 SCRIPTS AND FUNCTIONS 20
3 Scripts and functions
An M-le is a regular text le containing MATLAB commands, saved with the lename extension
.m. There are two types, scripts and functions. MATLAB comes with a pretty good editor that is
tightly integrated into the environment. Start it using open or edit. However, you are free to use
any text editor.
An M-le should be saved in the path in order to be executed. The path is just a list of direc-
tories (folders) in which MATLAB will look for les. Use editpath or menus to see and change
the path.
There is no need to compile either type of M-le. Simply type in the name of the le (without the
extension) in order to run it. Changes that are saved to disk will be included in the next call to the
function or script. (You can alter this behavior with mlock.)
One important type of statement in an M-le is a comment, which is indicated by a percent
sign %. Any text on the same line after a percent sign is ignored (unless % appears as part of
a string in quotes). Furthermore, the rst contiguous block of comments in an M-le serves as
documentation for the le and will be typed out in the command window if help is used on the
le. For instance, say the following is saved as myscript.m on the path:
% This script solves the nasty homework problem assigned by
% Professor Driscoll.
x = rand(1); % Hell never notice.
Then at the prompt one would nd
>> help myscript
This script solves the nasty homework problem assigned by
Professor Driscoll.
3.1 Using scripts effectively
A script is mostly useful as a driver for a multistep task. The commands in a script are literally
interpreted as though they were typed at the prompt. Good reasons to use scripts are
Creating or revising a long, complex sequence of commands.
Reproducing or interpreting your work at a later time.
Running a CPU-intensive job in the background, allowing you to log off.
The last point here refers specically to UNIX. For example, suppose you wrote a script called
run.m that said:
result = execute_big_routine(1);
result = another_big_routine(result);
result = an_even_bigger_routine(result);
save rundata result
3 SCRIPTS AND FUNCTIONS 21
At the UNIX prompt in the directory of run.m, you would enter (using csh style)
nice +19 matlab < run.m >! run.log &
which would cause your script to run in the background with low priority. The job will continue
to run until nished, even if you log off. The output that would have been typed to the screen is
redirected to run.log. You will usually need at least one save command to save your results.
Use it often in the script in case of a crash or other interruption. Also take pains to avoid taking
huge chunks of memory or disk space when running in an unattended mode.
3.2 Functions
Functions are the main way to extend the capabilities of MATLAB. Each function must start with
a line such as
function [out1,out2] = myfun(in1,in2,in3)
The variables in1, etc. are input arguments, and out1 etc. are output arguments. You can have
as many as you like of each type (including zero) and call them whatever you want. The name
myfun should match the name of the disk le.
Here is a function that implements (badly, it turns out) the quadratic formula.
function [x1,x2] = quadform(a,b,c)
d = sqrt(b2 - 4*a*c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
From MATLAB you could call
>> [r1,r2] = quadform(1,-2,1)
r1 =
1
r2 =
1
One of the most important features of a function is its local workspace. Any arguments or
other variables created while the function executes are available only to the executing function
statements. Conversely, variables in the command-line workspace (called the base workspace)
are normally not visible to the function. If during the function execution, more functions are
called, each of those calls also sets up a private workspace. These restrictions are called scoping,
and they make it possible to write complex programs without worrying about name clashes. The
values of the input arguments are copies of the original data, so any changes you make to themwill
not change anything outside the functions scope.
4
In general, the only communication between
4
MATLAB does avoid copying (i.e., passes by reference) if the function never alters the data.
3 SCRIPTS AND FUNCTIONS 22
a function and its caller is through the input and output arguments (though see section 4.3 for
exceptions). You can always see the variables dened in the current workspace by typing who or
whos.
A single M-le may hold more than one function denition. A new function header line in a
le ends the primary function and starts a new subfunction. As a silly example, consider
function [x1,x2] = quadform(a,b,c)
d = discrim(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
function D = discrim(a,b,c)
D = sqrt(b2 - 4*a*c);
A subfunction has its own workspace; thus, changes made to a inside discrim would not prop-
agate into the rest of quadform. In addition, the subfunctions themselves have a limited scope.
In the example the subfunction discrim is available only to the primary function quadform, not
to the command line.
5
Another important aspect of function M-les is that most of the functions built into MATLAB
(except core math functions) are themselves M-les that you can read and copy. This is an excellent
way to learn good programming practiceand dirty tricks.
3.3 Debugging and proling
Here are Tobys Fundamental Laws of Computer Programming:
1. It never works the rst time.
2. It could always work better.
To debug a program that doesnt work, you can set breakpoints in one or more functions. (See
the Breakpoints menu in the Editor.) When MATLAB reaches a breakpoint, it halts and lets you
inspect and modify all the variables currently in scopein fact, you can do anything at all from
the command line. You can then continue execution normally or step by step. Its also possible to
set non-specic breakpoints for error and warning conditions. See help debug for all the details.
Sometimes a program spends most of its running time on just a few lines of code. These lines
are then obvious candidates for optimization. You can nd such lines by proling, which keeps
track of time spent on every line of every function. Proling is also a great way to determine
function dependencies (who calls whom). Turn it on by entering profile on. After running
functions of interest, type profile report to get a report in your web browser. When you
dont need proling any more, enter profile off to avoid slowing down execution.
5
In other words, MATLAB uses only directory listings to see what functions are available at the prompt. However,
see section 3.5.
3 SCRIPTS AND FUNCTIONS 23
3.4 Inline functions
From time to time you may need a quick function denition that is temporaryyou dont care if
the function is around tomorrow. You can avoid writing M-les for these functions using a special
syntax. For example:
>> sc = inline(sin(x) + cos(x))
sc = Inline function: sc(x) = sin(x) + cos(x)
>> sc([0 pi/4 pi/2 3*pi/4 pi])
ans =
1.0000 1.4142 1.0000 0.0000 -1.0000
You can also dene functions of more than one variable, and name the variables explicitly:
>> w = inline(cos(x - c*t),x,t,c)
w =
Inline function: w(x,t,c) = cos(x - c*t)
>> w(pi,1,pi/2)
ans =
6.1232e-17
One use of inline functions is described in section 3.5.
3.5 Function functions
In many cases you need to use the name of a function as an argument to another function. For
example, the function fzero nds a root of a scalar function of one variable. So we could say
>> fzero(sin,3)
ans =
3.1416
>> fzero(exp(x)-3*x,1)
ans =
0.6191
If you need to nd the root of a more complicated function, or a function with a parameter, then
you can write it in an M-le and pass the name of that function. Say we have
function f = demo(x,a)
exp(x) - a*x;
Then we can use
>> fzero(@demo,1,[],3)
ans =
0.6191
3 SCRIPTS AND FUNCTIONS 24
>> fzero(@demo,1,[],4)
ans =
0.3574
Here we used the empty matrix [] as a placeholder so that fzero knows that the last argument
is a parameter. (The online help tells you that the third argument is reserved for another use.)
Note the new syntax: @demo is called a function handle and it gives fzero a way to accept
your function as an input argument. See help funfun to get a list of all of MATLABs function
functions for optimization, integration, and differential equations.
Function handles are also a way to get subfunctions passed outside of their parents. Consider
this example.
function answer = myfun(data)
% ...blah, blah...
r = fzero(@solveit,x0);
% ...blah, blah...
function f = solveit(x)
f = exp(1+cos(x)) - 1.5;
Ordinarily fzero could not be aware of the subfunction solveit, but when the primary myfun
creates a handle to it, then it can be used anywhere. This allows you to keep related functions in
just one le, and its often useful in rootnding, optimization, and solving differential equations.
You will probably have to write function functions of your own. Say you want to use the
bisection method of root nding. Here is a (crude) version.
function x = bisect(f,a,b)
fa = feval(f,a);
fb = feval(f,b);
while (b-a) > 1e-8
m = (a+b)/2;
fm = feval(f,m);
if fa*fm < 0
b = m; fb = fm;
else
a = m; fa = fm;
end
end
x = (a+b)/2;
(The full descriptions of while and if are in section 4.1.) Note how feval is used to evaluate
the generic function f. The syntax f(a) would produce an error in most cases. Now we can call
>> bisect(@sin,3,4)
3 SCRIPTS AND FUNCTIONS 25
ans =
3.1416
To see how to use optional extra parameters in bisect as we did with fzero, see section 7.2.
3.6 Exercises
1. Write a function quadform2 that implements the quadratic formula differently fromquadform
above (page 21). Once d is computed, use it to nd
x
1
=
b sign(b)d
2a
,
which is the root of largest magnitude, and then use the identity x
1
x
2
= c/a to nd x
2
.
Use both quadform and quadform2 to nd the roots of x
2
(10
7
+10
7
)x +1. Do you see
why quadform2 is better?
4 MORE ON FUNCTIONS 26
4 More on functions
4.1 Loops and conditionals
To write programs of any complexity you need to be able to use iteration and decision making.
These elements are available in MATLAB much like they are in any other major language. For
decisions, there are if and switch, and for iterations there are for and while.
if and switch
Here is an example illustrating most of the features of if.
if isinf(x) || isreal(x)
disp(Bad input!)
y = NaN;
elseif (x == round(x)) && (x > 0)
y = prod(1:x-1)
else
y = gamma(x)
end
The conditions for if statements may involve the relational operators of Table 3, or functions
such as isinf that return logical values. Numerical values can also be used, with nonzero mean-
ing true, but if x=0 is better practice than if x.
Individual conditions can be combined using
&& (logical AND) || (logical OR) (logical NOT)
Compound conditions can be short-circuited. As a condition is evaluated from left to right, it may
become obvious before the end that truth or falsity is assured. At that point, evaluation of the
condition is halted. This makes it convenient to write things like
if (length(x) >= 3) && (x(3)==1)
that are otherwise awkward.
The if/elseif construct is ne when only a few options are present. When a large number
of options are possible, its customary to use switch instead. For instance:
switch units
case length
disp(meters)
case volume
disp(liters)
case time
disp(seconds)
otherwise
disp(I give up)
end
4 MORE ON FUNCTIONS 27
The switch expression can be a string or a number. The rst matching case has its commands
executed.
6
If otherwise is present, it gives a default option if no case matches.
for and while
This illustrates the most common type of for loop:
>> f = [1 1];
>> for n = 3:10
f(n) = f(n-1) + f(n-2);
end
You can have as many statements as you like in the body of the loop. The value of the index n
will change from 3 to 10, with an execution of the body after each assignment. But remember that
3:10 is really just a row vector. In fact, you can use any row vector in a for loop, not just one
created by a colon. For example,
>> x = 1:100; s = 0;
>> for j = find(isprime(x))
s = s + x(j);
end
This nds the sum of all primes less than 100. (For a better version, though, see page 42.)
A warning: If you are using complex numbers, you might want to avoid using i as the loop
index. Once assigned a value by the loop, i will no longer equal
1. However, you can always
use 1i for the imaginary unit.
As we saw in the bisection program on page 24, it is sometimes necessary to repeat statements
based on a condition rather than a xed number of times. This is done with while.
while x > 1
x = x/2;
end
The condition is evaluated before the body is executed, so it is possible to get zero iterations. Its
often a good idea to limit the number of repetitions, to avoid innite loops (as could happen above
if x==Inf). This can be done using break.
n = 0;
while x > 1
x = x/2;
n = n+1;
if n > 50, break, end
end
A break immediately jumps execution to the rst statement after the loop.
6
Execution does not fall through as in C.
4 MORE ON FUNCTIONS 28
4.2 Errors and warnings
MATLAB functions may encounter statements that are impossible to execute (for example, multi-
plication of incompatible matrices). In that case an error is thrown: execution of the function halts,
a message is displayed, and the output arguments of the function are ignored. You can throw er-
rors in your own functions with the error statement, called with a string that is displayed as
the message. Similar to an error is a warning, which displays a message but allows execution to
continue. You can create these using warning.
Sometimes you would like the ability to recover from an error in a subroutine and continue
with a contingency plan. This can be done using the trycatch construct. For example, the
following will continue asking for a statement until you give it one that executes successfully.
done = false;
while done
state = input(Enter a valid statement: ,s);
try
eval(state);
done = true;
catch
disp(That was not a valid statement!)
end
end
Within the catch block you can nd the most recent error message using lasterr.
4.3 Scoping exceptions
Once in a while the scoping rules for functions get in the way. Although you can almost always
do what you need within the rules, its nice to know how to bend them.
The least useful and most potentially troublesome violation of scoping comes from global
variables. Any function (or the user at the command line) can declares a variable to be global
before assigning it a value. Then any other workspace may also declare it global and see or change
its value. At one time global values were more or less necessary in MATLAB, but that is no longer
the case. They should not be used, for example, to pass extra parameters into function functions.
As described in section 3.5, there are better and more stable means of doing so. The primary
problem with global variables is that it becomes possible to have conicting names, or to lose
track of what functions may modify a value. Input and output parameters make this information
much more apparent.
A more interesting type of variable is called persistent. One use of persistent variables is to
compute some preliminary data that needs to be used on subsequent calls. Although the data
could be returned to the caller and passed back in to the function, that is inconvenient when such
data are meaningless to the caller. Consider this example.
function y = persistfib(n)
persistent f
4 MORE ON FUNCTIONS 29
if length(f)<n
f = [1 1];
for k = 3:n
f(k) = f(k-2) + f(k-1);
end
end
y = f(n);
The rst time this function is called, f will be empty.
7
So the loop will run, dening f as a vector
of Fibonacci numbers up to the needed length. Unlike an ordinary variable, though, f is not
destroyed when the function exits, and if a future call requests a previously computed value,
it will be returned for free. The same effect could be achieved with a global variable, but a
persistent variable is accessible only to the function that created it. In fact, different functions
can use the same name for a persistent variable without interference.
A more radical violation of scoping rules are the functions assignin and evalin. These
allow the assignment of variables or execution of statements in a workspace other than the local
oneeither the callers or the base workspace. This can be used to change the state of the users
environment invisibly. While occasionally indispensable, this ability should be sipped delicately,
not gulped.
4.4 Exercises
1. Write a function newton(fdf,x0,tol) that implements Newtons iteration for rootnd-
ing on a scalar function:
x
n+1
= x
n
f (x
n
)
f
(x
n
)
The rst input is a handle to a function computing f and f
,
where h = (b a)/n and x
i
= a +ih. Test your function on sin(x) +cos(x) for 0 x /3.
For a greater challenge, write a function simp for Simpsons rule,
_
b
a
f (x) dx
h
3
_
f (x
0
) +4 f (x
1
) +2 f (x
2
) +4 f (x
3
) +2 f (x
4
) + +4 f (x
n1
) + f (x
n
)
.
7
persistent variables, unlike others, are initialized to the empty matrix.
4 MORE ON FUNCTIONS 30
(This formula requires n to be even. You may choose to check the input for this.)
4. The degree-n Chebyshev polynomial is dened by
T
n
(x) = cos
_
n cos
1
(x)
, 1 x 1.
We have T
0
(x) = 1, T
1
(x) = x, and a recursion relation:
T
n+1
(x) = 2xT
n
(x) T
n1
(x), n 1.
Write a function chebeval(x,N) that evaluates all the Chebyshev polynomials of degree
less than or equal to N at all of the points in column vector x. The result should be a matrix
of size length(x) by N+1.
5. One way to compute the exponential function e
x
is to use its Taylor series expansion around
x = 0. Unfortunately, many terms are required if |x| is large. But a special property of the
exponential is that e
2x
= (e
x
)
2
. This leads to a scaling and squaring method: Divide x by
2 repeatedly until |x| < 1/2, use a Taylor series (16 terms should be more than enough),
and square the result repeatedly. Write a function expss(x) that does this. (The function
polyval can help with evaluating the Taylor expansion.) Test your function on x values
30, 3, 3, 30.
6. Let x and y be column vectors of the vertices of a polygon (given in order). Write func-
tions polyperim(x,y) and polyarea(x,y) that compute the perimeter and area of the
polygon. For the area, use a formula based on Greens theorem:
A =
1
2
k=1
x
k
y
k+1
x
k+1
y
k
.
Here n is the number of vertices and its understood that x
n+1
= x
1
and y
n+1
= y
1
.
7. If a data source produces symbol k with probability p
k
, the rst-order entropy of the source is
dened as
H
1
=
k
p
k
log
2
p
k
.
Essentially H
1
is the number of bits needed per symbol to encode a long message; i.e., it mea-
sures the amount of information content (and therefore the potential success of compression
strategies). The value H
1
= 0 corresponds to one symbol onlyno informationwhile for
M symbols of equal probability, H
1
= log
2
M.
Write a function [H,M] = entropy(v) that computes entropy for a vector v. The prob-
abilities should be computed empirically, by counting occurrences of each unique symbol
and dividing by the length of v. (The built-in functions find and unique may be help-
ful.) Try your function on some carefully selected examples with different levels of informa-
tion content. Once source of data is to use load clown; v = X(:);. You can also nd
data sources from help gallery and (if you have the Image Processing Toolbox) help
imdemos. You might also want to stick with integer data by using round.
5 GRAPHICS 31
5 Graphics
Graphical display is one of MATLABs greatest strengthsand most complicated subjects. The
basics are quite simple, but you also get complete control over practically every aspect of each
graph, and with that power comes complexity.
Graphical objects are classied by type. The available types lie in a strict hierarchy, as shown
in Figure 1. Each gure has its own window. Inside a gure is one or more axes (ignore the other
types on this level until section 8). You can make an existing gure or axes current by clicking
on it.
Inside the axes are drawn data-bearing objects like lines and surfaces. While there are functions
called line and surface, you will very rarely use those. Instead you use friendlier functions that
create these object types.
5.1 2-D plots
The most fundamental plotting command is plot. Basically, it plots points, given by vectors of x
and y coordinates, with straight lines drawn in between them.
Here is a simple example.
>> t = pi*(0:0.02:2);
>> plot(t,sin(t))
A new line object is drawn in the current axes of the current gure (these are created if necessary).
The line may appear to be a smooth, continuous curve. However, its really just a game of connect
the dots, as you can see by entering
>> plot(t,sin(t),o-)
Now a circle is drawn at each of the points that are being connected. Just as t and sin(t) are
really vectors, not functions, curves in MATLAB are really joined line segments.
8
If you now say
8
A signicant difference from Maple and other packages is that if the viewpoint is rescaled to zoom in, the dots
are not recomputed to give a smooth curve.
Figure 1: Graphics object hierarchy.
5 GRAPHICS 32
>> plot(t,cos(t),r)
you will get a red curve representing cos(t). The curve you drew earlier is erased. To add curves,
rather than replacing them, use hold.
>> plot(t,sin(t),b)
>> hold on
>> plot(t,cos(t),r)
You can also do multiple curves in one shot, if you use column vectors:
>> t = (0:0.01:1);
>> plot(t,[t t.2 t.3])
Here you get no control (well, not easily) over the colors used.
Other useful 2D plotting commands are given in Table 6. See a bunch more by typing help
graph2d.
Table 6: 2D plotting commands
figure Open a new gure window.
subplot Multiple axes in one gure.
semilogx, semilogy, loglog Logarithmic axis scaling.
axis, xlim, ylim Axes limits.
legend Legend for multiple curves.
print Send to printer.
You may zoom in to particular portions of a plot by clicking on the magnifying glass icon in
the gure and drawing a rectangle. See help zoom for more details.
5.2 3-D plots
Plots of surfaces and such for functions f (x, y) also operate on the connect the dots principle,
but the details are more difcult. The rst step is to create a grid of points in the xy-plane. These
are the points where f is evaluated to get the dots.
Here is a typical example:
>> x = pi*(0:0.02:1);
>> y = 2*x;
>> [X,Y] = meshgrid(x,y);
>> surf(X,Y,sin(X.2+Y))
The key step is in using meshgrid to make the xy grid. To see this underlying grid, try plot(X(:),Y(:),k.).
The command surf makes a solid-looking surface; mesh makes a wireframe surface. In both
cases color as well as apparent height signal the values of f . Use the rotation button in the gure
window (counterclockwise arrow) to manipulate the 3D viewpoint.
The most common 3D plotting commands are shown in Table 7.
5 GRAPHICS 33
Table 7: 3D plotting commands
surf, mesh, waterfall Surfaces in 3D.
colorbar Show color scaling.
plot3 Curves in space.
pcolor Top view of a colored surface.
contour, contourf Contour plot.
5.3 Annotation
A bare graph with no labels or title is rarely useful. The last step before printing or saving is
usually to label the axes and maybe give a title. For example,
>> t = 2*pi*(0:0.01:1);
>> plot(t,sin(t))
>> xlabel(time)
>> ylabel(amplitude)
>> title(Simple Harmonic Oscillator)
By clicking on the A button in the gure window, you can add text comments anywhere on
the graph. You can also use the arrow button to draw arrows on the graph. This combination is
often a better way to label curves than a legend.
5.4 Quick function plots
Sometimes you dont want the hassle of picking out the plotting points for yourself, especially if
the function varies more in some places than in others. There is a series of commands for plotting
functional expressions directly.
>> ezplot(exp(3*sin(x)-cos(2*x)),[0 4])
>> ezsurf(1/(1+x2+2*y2),[-3 3],[-3 3])
>> ezcontour(x2-y2,[-1 1],[-1 1])
5.5 Handles and properties
Every rendered object has a handle, which is basically an ID number. This handle can be used
to look at and change the objects properties, which control just about every aspect of the objects
appearance and behavior. (You can see a description of all property names in the Help Browser.)
Handles are returned as outputs of most plotting commands. You can get the handles of the
current gure, current axes, or current object (most recently clicked) fromgcf, gca, and gco. The
handle of a gure is just the integer number of the gure window, and the Root object has handle
zero.
Properties are accessed by the functions get and set, or by enabling Edit Plot in a gures
Tools menu and double-clicking on the object. Here is just a taste of what you can do:
5 GRAPHICS 34
>> h = plot(t,sin(t))
>> set(h,color,m,linewidth,2,marker,s)
>> set(gca,pos,[0 0 1 1],visible,off)
Here is a way to make a dynamic graph or simple animation:
>> clf, axis([-2 2 -2 2]), axis equal
>> h = line(NaN,NaN,marker,o,linesty,-,erasemode,none);
>> t = 6*pi*(0:0.02:1);
>> for n = 1:length(t)
set(h,xdata,2*cos(t(1:n)),ydata,sin(t(1:n)))
pause(0.05)
end
Because of the way handle graphics works, plots in MATLAB are usually created rst in a basic
formand then modied to look exactly as you want. An exception is modifying property defaults.
Every property of every graphics type has a default value used if nothing else is specied for an
object. You can change the default behavior by resetting the defaults at any level above the objects
type. For instance, to make sure that all future Text objects in the current gure have font size 10,
say
>> set(gcf,defaulttextfontsize,10)
If you want this to be the default in all current and future gures, use the root object 0 rather than
gcf.
5.6 Color
The coloring of lines and text is easy to understand. Each object has a Color property that can be
assigned an RGB (red, green, blue) vector whose entries are between zero and one. In addition
many one-letter string abbreviations are understood (see help plot).
Surfaces are different. To begin with, the edges and faces of a surface may have different
color schemes, accessed by EdgeColor and FaceColor properties. You specify color data at all the
points of your surface. In between the points the color is determined by shading. In at shading,
each face or mesh line has constant color determined by one boundary point. In interpolated
shading, the color is determined by interpolation of the boundary values. While interpolated
shading makes much smoother and prettier pictures, it can be very slow to render, particularly on
printers.
9
Finally, there is faceted shading which uses at shading for the faces and black for the
edges. You select the shading of a surface by calling shading after the surface is created.
Furthermore, there are two models for setting color data:
Indirect Also called indexed. The colors are not assigned directly, but instead by indexes in a
lookup table called a colormap. This is how things work by default.
Direct Also called truecolor. You specify RGB values at each point of the data.
9
In fact its often faster on a printer to interpolate the data yourself and print it with at shading. See interp2 to
get started on this.
5 GRAPHICS 35
Truecolor is more straightforward, but it produces bigger les and is more platform-dependent.
Use it only for photorealistic images.
Heres howindirect mapping works. Just as a surface has XData, YData, and ZData properties,
with axes limits in each dimension, it also has a CData property and color axis limits. The color
axis is mapped linearly to the colormap, which is a 64 3 list of RGB values stored in the gure.
A points CData value is located relative to the color axis limits in order to look up its color in
the colormap. By changing the gures colormap, you can change all the surface colors instantly.
Consider these examples:
>> [X,Y,Z] = peaks; % some built-in data
>> surf(X,Y,Z), colorbar
>> caxis % current color axis limits
ans =
-6.5466 8.0752
>> caxis([-8 8]), colorbar % a symmetric scheme
>> shading interp
>> colormap pink
>> colormap gray
>> colormap(flipud(gray)) % reverse order
By default, the CData of a surface is equal to its ZData. But you can make it different and
thereby display more information. One use of this is for functions of a complex variable.
>> [T,R] = meshgrid(2*pi*(0:0.02:1),0:0.05:1);
>> [X,Y] = pol2cart(T,R);
>> Z = X + 1i*Y;
>> W = Z.2;
>> surf(X,Y,abs(W),angle(W)/pi)
>> axis equal, colorbar
>> colormap hsv % ideal for this situation
5.7 Saving gures
It often happens that a gure needs to be changed long after its creation. You can save the com-
mands that created the gure as a script (section 3.1), but this has drawbacks. If the data take a
long time to generate, rerunning the script will waste time. Also, graphical edits will be lost.
Instead, you can save gures in a native format. Just enter
>> saveas(gcf,myfig.fig)
to save the current gure in a le myfig.fig. Later you can enter openfig myfig to recreate
it, and continue editing.
5.8 Graphics for publication
There are three major issues that come up when you want to include some MATLAB graphics in
a document:
5 GRAPHICS 36
le format
size and position
color
It helps to realize that what you see on the screen is not really what you get on paper.
To a certain extent, the le format you should use depends on your computer platform and
word processor. The big difference is between vector (representing the lines in an image) and
bitmap (a literal pixel-by-pixel snapshot) graphics. Bitmaps are great for photographs, but for
most other scientic applications they are a bad idea. These formats x the resolution of your
image forever, but the resolution of your screen, your printer, and a journals printer are all very
different. These formats include GIF, JPEG, PNG, and TIFF.
10
Vector formats are usually a much
better choice. They include EPS and WMF.
EPS les (encapsulated postscript) are usually the right choice for documents in L
A
T
E
X. (They
also work in MS Word if you use a postscript printer.) For example, to save MATLAB Figure 2 as
le myfig.eps, use
>> saveas(2,myfig.eps)
A common problem with publishing MATLAB graphs has to do with size. By default, MAT-
LAB gures are rendered at 8 inches by 6 inches on paper. This is great for private use, but too
large for most journal papers. Its easy in L
A
T
E
X and other word processors to rescale the image to
a more reasonable size. Most of the time, this is the wrong way to do things. The proper way is to
scale the gure before saving it.
Here are two versions of an annotated graph. On the left, the gure was saved at default size
and then rescaled in L
A
T
E
X. On the right, the gure was rescaled rst.
On the gure that is shrunk in L
A
T
E
X, the text has become so small that its hard to read. To pre-
shrink a gure, before saving you need to enter
10
JPEG is especially bad for line drawings since it is also lossy.
5 GRAPHICS 37
>> set(gcf,paperpos,[0 0 3 2.25])
where the units are in inches. (Or see the File/Page Setup menu of the gure.) Unfortunately,
sometimes the axes or other elements need to be repositioned. To make the display match the
paper output, you should enter
>> set(gcf,unit,inch,pos,[0 0 3 2.25])
It might be desirable to incorporate such changes into a function. Here is one that also forces a
smaller font size of 8 for all Axes and Text objects (see section 5.5):
function h = journalfig(size)
pos = [0 0 size(:)];
h = figure(unit,inch,position,pos,paperpos,pos);
set(h,defaultaxesfontsize,8,defaulttextfontsize,8)
movegui(h,northeast)
Most monitors are in color, but most journals do not accept color. Colored lines are automat-
ically converted to black when saved in a non-color format. The colors of surfaces are converted
to grayscale, but by default the colors on a surface range from blue to red, which in grayscale are
hard to tell apart. You might consider using colormap(gray) or colormap(flipud(gray)),
whichever gives less total black. Finally, the edges of mesh surfaces are also converted to gray,
and this usually looks bad. Make them all black by entering
>> set(findobj(gcf,type,surface),edgecolor,k)
If you do want to publish color gures, you must add an epsc argument in saveas.
I recommend saving each gure in graphical (EPS) format and in fig format (section 5.7) with
the same name, all in a separate gure directory for your paper. That way you have the gures,
and the means to change or recreate them, all in one place.
5.9 Exercises
1. Recall the identity
e = lim
n
r
n
, r
n
=
_
1 +
1
n
_
n
.
Make a standard and a log-log plot of e r
n
for n = 5, 10, 15, . . . , 500. What does the log-log
plot say about the asymptotic behavior of e r
n
?
2. Play the chaos game. Let P
1
, P
2
, and P
3
be the vertices of an equilateral triangle. Start
with a point anywhere inside the triangle. At random, pick one of the three vertices and
move halfway toward it. Repeat indenitely. If you plot all the points obtained, a very clear
pattern will emerge. (Hint: This is particularly easy to do if you use complex numbers. If z
is complex, then plot(z) is equivalent to plot(real(z),imag(z)).)
3. Make surface plots of the following functions over the given ranges.
5 GRAPHICS 38
(a) (x
2
+3y
2
)e
x
2
y
2
, 3 x 3, 3 y 3
(b) 3y/(x
2
+ y
2
+1), |x| 2, |y| 4
(c) |x| + |y|, |x| 1, |y| 1
4. Make contour plots of the functions in the previous exercise.
5. Make a contour plot of
f (x, y) = e
(4x
2
+2y
2
)
cos(8x) + e
3((2x+1/2)
2
+2y
2
)
for 1.5 < x < 1.5, 2.5 < y < 2.5, showing only the contour at the level f (x, y) = 0.001.
You should see a friendly message.
6. Parametric surfaces are easily done in MATLAB. Plot the surface represented by
x = u(3 +cos(v)) cos(2u), y = u(3 +cos(v)) sin(2u), z = u sin(v) 3u
for 0 u 2, 0 v 2. (Dene U and V as a grid over the specied limits, use them to
dene X, Y, and Z, and then use surf(X,Y,Z).)
6 OPTIMIZING PERFORMANCE 39
6 Optimizing performance
One often hears the complaint that MATLAB is too slow. While its true that even the best
MATLAB code may not keep up with good C code, the gap is not necessarily wide. In fact, on
core linear algebra routines such as matrix multiplication and linear system solution, there is very
little difference in performance. By writing good MATLAB programs, you can often nearly recover
the speed of compiled code.
11
Its good to start by proling your code (section 3.3) to nd out where the bottlenecks are.
6.1 Use functions, not scripts
Scripts are always read and executed one line at a time (interpreted). No matter how many times
you execute the same script, MATLAB must spend time parsing your syntax. By contrast, func-
tions are effectively compiled into memory when called for the rst time or modied. Subsequent
invocations skip the interpretation step.
As a rule of thumb, scripts should be called only from the command line, and they should
themselves call only functions, not other scripts.
6.2 Preallocate memory
MATLAB hides the tedious process of allocating memory for variables. This generosity can cause
you to waste a lot of runtime, though. Consider an implementation of Eulers method for the
vector differential equation y