A Matlab Tutorial
A Matlab Tutorial
Ed Overman
Department of Mathematics
The Ohio State University
(August 12, 2016 2:07 p.m.)
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 3
1 Scalar Calculations . . . . . . . . . . . . . . . . . . . . . . 6
1.1 Simple Arithmetical Operations . . . . . . . . . . . . . . . . . 6
1.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Round-off Errors . . . . . . . . . . . . . . . . . . . . . . 9
1.4 Formatting Printing . . . . . . . . . . . . . . . . . . . . . 10
1.5 Common Mathematical Functions . . . . . . . . . . . . . . . . 11
1.6 Complex Numbers . . . . . . . . . . . . . . . . . . . . . 13
1.7 Script M-files . . . . . . . . . . . . . . . . . . . . . . . 14
1.8 Help! . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.9 Be Able To Do . . . . . . . . . . . . . . . . . . . . . . 17
2 Arrays: Vector and Matrix Calculations . . . . . . . . . . . . . . . 17
2.1 Generating Matrices . . . . . . . . . . . . . . . . . . . . . 18
2.2 The Colon Operator . . . . . . . . . . . . . . . . . . . . . 22
2.3 Manipulating Vectors and Matrices . . . . . . . . . . . . . . . . 23
2.4 Simple Arithmetical Operations . . . . . . . . . . . . . . . . . 28
2.5 Operator Precedence . . . . . . . . . . . . . . . . . . . . 31
2.6 Be Careful! . . . . . . . . . . . . . . . . . . . . . . . 32
2.7 Common Mathematical Functions . . . . . . . . . . . . . . . . 34
2.8 Data Manipulation Functions . . . . . . . . . . . . . . . . . . 34
2.9 Advanced Topic: Multidimensional Arrays . . . . . . . . . . . . . . 37
2.10 Be Able To Do . . . . . . . . . . . . . . . . . . . . . . 38
3 Anonymous Functions, Strings, and Other Data Types . . . . . . . . . . 39
3.1 Anonymous Functions . . . . . . . . . . . . . . . . . . . . 40
3.2 Passing Functions as Arguments . . . . . . . . . . . . . . . . . 41
3.3 Strings . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.4 Cell Arrays and Structures . . . . . . . . . . . . . . . . . . . 43
3.5 Advanced Topic: Data Types and Classes . . . . . . . . . . . . . . 46
3.6 Be Able To Do . . . . . . . . . . . . . . . . . . . . . . 48
4 Graphics . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.1 Two-Dimensional Graphics . . . . . . . . . . . . . . . . . . . 49
4.2 Three-Dimensional Graphics . . . . . . . . . . . . . . . . . . 59
4.3 Advanced Topic: Functions . . . . . . . . . . . . . . . . . . 61
4.4 Advanced Topic: Handles and Properties . . . . . . . . . . . . . . 66
4.5 Advanced Topic: GUIs (Graphical User Interfaces) . . . . . . . . . . . 68
4.6 Advanced Topic: Making Movies . . . . . . . . . . . . . . . . . 74
4.7 Be Able To Do . . . . . . . . . . . . . . . . . . . . . . 77
5 Solving Linear Systems of Equations . . . . . . . . . . . . . . . . 77
5.1 Square Linear Systems . . . . . . . . . . . . . . . . . . . . 77
5.2 Catastrophic Round-Off Errors . . . . . . . . . . . . . . . . . 80
5.3 Overdetermined and Underdetermined Linear Systems . . . . . . . . . . 81
6 File Input-Output . . . . . . . . . . . . . . . . . . . . . . 83
7 Some Useful Linear Algebra Functions . . . . . . . . . . . . . . . 84
8 Programming in MATLAB . . . . . . . . . . . . . . . . . . . 91
8.1 Control Flow and Logical Variables . . . . . . . . . . . . . . . . 91
8.2 Matrix Relational Operators and Logical Operators . . . . . . . . . . . 95
8.3 Function M-files . . . . . . . . . . . . . . . . . . . . . . 99
8.4 Odds and Ends . . . . . . . . . . . . . . . . . . . . . . 111
8.5 Advanced Topic: Vectorizing Code . . . . . . . . . . . . . . . . 113
9 Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . 116
10 Initial-Value Ordinary Differential Equations . . . . . . . . . . . . . 119
10.1 Basic Functions . . . . . . . . . . . . . . . . . . . . . . 119
10.2 Advanced Functions . . . . . . . . . . . . . . . . . . . . . 124
11 Boundary-Value Ordinary Differential Equations . . . . . . . . . . . 130
12 Polynomials and Polynomial Functions . . . . . . . . . . . . . . . 133
13 Numerical Operations on Functions . . . . . . . . . . . . . . . . 136
14 Discrete Fourier Transform . . . . . . . . . . . . . . . . . . . 139
15 Mathematical Functions Applied to Matrices . . . . . . . . . . . . . 146
Appendix: Reference Tables . . . . . . . . . . . . . . . . . . . . 149
Arithmetical Operators . . . . . . . . . . . . . . . . . . . . . 149
Special Characters . . . . . . . . . . . . . . . . . . . . . . . 149
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . 150
Predefined Variables . . . . . . . . . . . . . . . . . . . . . . 150
Format Options . . . . . . . . . . . . . . . . . . . . . . . . 150
Some Common Mathematical Functions . . . . . . . . . . . . . . . . 151
Input-Output Functions . . . . . . . . . . . . . . . . . . . . . 152
Arithmetical Matrix Operations . . . . . . . . . . . . . . . . . . . 152
Elementary Matrices . . . . . . . . . . . . . . . . . . . . . . 153
Specialized Matrices . . . . . . . . . . . . . . . . . . . . . . 153
Elementary Matrix Operations . . . . . . . . . . . . . . . . . . . 153
Manipulating Matrices . . . . . . . . . . . . . . . . . . . . . . 154
Odds and Ends . . . . . . . . . . . . . . . . . . . . . . . . 154
Two-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . 155
Three-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . 155
Advanced Graphics Features . . . . . . . . . . . . . . . . . . . . 156
String Functions, Cell Arrays, Structures, and Classes . . . . . . . . . . . . 157
Data Manipulation Functions . . . . . . . . . . . . . . . . . . . 157
Some Useful Functions in Linear Algebra . . . . . . . . . . . . . . . . 158
Logical and Relational Operators . . . . . . . . . . . . . . . . . . 158
Control Flow . . . . . . . . . . . . . . . . . . . . . . . . 158
Logical Functions . . . . . . . . . . . . . . . . . . . . . . . 159
Programming Language Functions . . . . . . . . . . . . . . . . . . 160
Debugging Commands . . . . . . . . . . . . . . . . . . . . . . 160
Discrete Fourier Transform . . . . . . . . . . . . . . . . . . . . 160
Sparse Matrix Functions . . . . . . . . . . . . . . . . . . . . . 161
Time Evolution ODE Solvers . . . . . . . . . . . . . . . . . . . . 161
Boundary-Value Solver . . . . . . . . . . . . . . . . . . . . . 161
Numerical Operations on Functions . . . . . . . . . . . . . . . . . . 161
Numerical Operations on Polynomials . . . . . . . . . . . . . . . . . 162
Matrix Functions . . . . . . . . . . . . . . . . . . . . . . . 162
Solutions To Exercises . . . . . . . . . . . . . . . . . . . . . . 163
ASCII Table . . . . . . . . . . . . . . . . . . . . . . . . . 167
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
2014
c Ed Overman
Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative
Commons Attribution-NonCommercial 4.0 Unported License, which is available at
creativecommons.org/licenses/by-nc/4.0/.
2
Introduction
MATLAB is an interactive software package which was developed to perform numerical calculations
on vectors and matrices. Initially, it was simply a MATrix LABoratory. However, today it is much more
powerful:
It can do quite sophisticated graphics in two and three dimensions.
It contains a high-level programming language (a baby C) which makes it quite easy to code com-
plicated algorithms involving vectors and matrices.
It can numerically solve nonlinear initial-value ordinary differential equations.
It can numerically solve nonlinear boundary-value ordinary differential equations.
It contains a wide variety of toolboxes which allow it to perform a wide range of applications from sci-
ence and engineering. Since users can write their own toolboxes, the breadth of applications is quite
amazing.
Mathematics is the basic building block of science and engineering, and MATLAB makes it easy to handle
many of the computations involved. You should not think of MATLAB as another complication program-
ming language, but as a powerful calculator that gives you fingertip access to exploring interesting prob-
lems in science, engineering, and mathematics. And this access is available by using only a small number
of commands and functions because MATLABs basic data element is a matrix (or an array).
This is a crucial feature of MATLAB it was designed to group large amounts of data in arrays and
to perform mathematical operations on this data as individual arrays rather than as groups of data. This
makes it very easy to apply complicated operations to the data, and it make it very difficult to do it
wrong. In high-level computer languages you would usually have to work on each piece of data separately
and use loops to cycle over all the pieces. In MATLAB this can frequently do complicated things in
one, or a few, statements (and no loops). In addition, in a high-level language many mathematical op-
erations require the use of sophisticated software packages, which you have to find and, much worse, to
understand since the interfaces to these packages are frequently quite complicated and the documentation
must be read and mastered. In MATLAB, on the other hand, these operations have simple and consistent
interfaces which are quite easy to master. For an overview of the capabilities of MATLAB, type
>> demo
in the Help Navigator and click on MATLAB.
This tutorial is designed to be a concise introduction to many of the capabilities of MATLAB. It makes
no attempt to cover either the range of topics or the depth of detail that you can find in a reference man-
ual, such as Mastering MATLAB 7 by Duane Hanselman and Bruce Littlefield (which is over 850 pages
long) or MATLAB Guide, 2nd edition by Desmond and Nicholas Higham (which is almost 400 pages long).
This tutorial was initially written to provide students with a free basic overview of functions which are
useful in an undergraduate course on linear algebra. Over the years it has grown to include courses in
ordinary differential equations, mathematical modelling, and numerical analysis. It also includes an intro-
duction to two- and three-dimensional graphics because graphics is often the preferred way to present the
results of calculations.
In this tutorial MATLAB is first introduced as a calculator and then as a plotting package. Only after-
wards are more technical topics discussed. We take this approach because most people are quite familiar
with calculators, and it is only a small step to understand how to apply these same techniques to matrices
rather than individual numbers or varibles. In addition, by viewing MATLAB as a simple but powerful
calculater, rather than as a complicated software package or computer language, you will be in the correct
frame of mind to use MATLAB.
You should view MATLAB as a tool that you are playing with trying ideas out and seeing how
they work. If an idea works, fine; if it doesnt, investigate further and figure out why. Maybe you misun-
derstood some MATLAB command/function, or maybe your idea needs some refinement. Play around
There is a technical distinction between a command and a function in MATLAB: input arguments to com-
mands are not enclosed in parentheses (they are separated by spaces) and there are no output arguments (i.e., a
command cannot be on the right-hand side of an equal sign). In reality, this is a very fine distinction since many
commands can be written as functions by putting the arguments between parentheses and separating them with
commas. We will generally use the terms interchangably.
3
interactively and figure it out. There are no hard and fast rules for figuring it out try things and see
what happens. Dont be afraid to make mistakes; MATLAB wont call you an idiot for making a mistake.
When you first learned to ride a bicycle, you fell down a lot and you looked pretty silly. But you kept
at it until you didnt fall down. You didnt study Newtons laws of motion and try to analyze the motion
of a bicycle; you didnt take classes in how to ride a bicycle; you didnt get videos from the library on how
to ride a bicycle. You just kept at it, possibly with the assistance of someone who steadied the bicycle and
gave you a little push to get you started. This is how you should learn MATLAB.
However, this tutorial is not designed for playing around. It is very ordered, because it has been de-
signed as a brief introduction to all the basic topics that I consider important and then as a reference
manual. It would be very useful for students to have a document which uses this play around approach
so you would learn topics by using them in exploring some exercise. This is how workbooks should be
written: present some exercise for students to investigate, and let them investigate it themselves. And
these exercises should be interesting, having some connection to physical or mathematical models that
the students or at least a reasonable fraction thereof have some knowledge of and some interest in.
This tutorial is designed to be a reference manual that could be used alongside such a workbook if only
someone would write it.
Summary of Contents
We have tried to make this tutorial as linear as possible so that the building blocks necessary for a sec-
tion are contained in preceding sections. This is not the best way to learn MATLAB, but it is a good way
to document it. In addition, we try to separate these building blocks and put them in short subsections so
that they are are easy to find and to understand. Next, we collect all the commands/functions discussed
in a subsection and put them in a box at the end along with a very brief discussion to make it easy to re-
member these commands. Finally, we collect them all and put them in the appendix, again boxed up by
topic. MATLAB has a HUGE number of commands/functions and this is one way to collect them for
easy reference.
Warning: Usually we do not discuss the complete behavior of these commands/functions, but only their
most \useful" behavior. Typing
>> help <command/function>
or
>> doc <command/function>
gives you complete information about the command/function.
Notation: help <command/function> means to enter whatever command/function you desire (without
the braces).
help command/function means to type these two words as written.
Section 1 of this tutorial discusses how to use MATLAB as a scalar calculator, and Section 2 how to
use it as a matrix calculator. Following this, you will be able to set up and solve the matrix equation
Ax = b where A is a square nonsingular matrix.
Section 4 discusses how to plot curves in two and three dimensions and how to plot surfaces in three di-
mensions. These three sections provide a basic introduction to MATLAB. At the end of each of these
three sections there is a subsection entitled Be Able To Do which contains sample exercises to make sure
you understand the basic commands/functions discussed. (Solutions are included.)
You have hopefully noticed that we skipped section 3. It discusses a number of minor topics. Since they
are useful in generating two- and three-dimensional plots, we have included it here.
The following sections delve more deeply into particular topics. Section 5 discusses how to find any and
all solutions of Ax = b where A Cmn need not be a square matrix; there might be no solutions, one
solution, or an infinite number to this linear system. When no solution exists, it discusses how to calcu-
late a least-squares solution (i.e., the best approximation to a solution). In addition, it discusses how
round-off errors can corrupt the solution, and how to determine if this is likely to occur.
Section 6 is quite brief and discusses advanced functions to input data into MATLAB and output it to
a file. (The basic functions are discussed in Section 4.1.) This is useful if the data is being shared between
various computer programs and/or software packages.
Section 7 discusses a number of functions which are useful in linear algebra and numerical linear alge-
bra. Probably the most useful of these is calculating some or all of the eigenvalues of a square matrix.
4
Section 8 discusses MATLAB as a programming language a very baby C. Since the basic data ele-
ment of MATLAB is a matrix, this programming language is very simple to learn and to use. Most of this
discussion focuses on writing your own MATLAB functions, called function m-files (which are similar to
functions in C and to functions, more generally subprograms, in Fortran). Using these functions, you can
code a complicated sequence of statements such that all these statements as well as all the the variables
used by these functions are hidden and will not affect the remainder of your MATLAB session. The only
way to pass data into and out of these functions is through the argument list.
Section 9 discusses how to generate sparse matrices (i.e., matrices where most of the elements are zero).
These matrices could have been discussed in Section 2, but we felt that it added too much complexity at
too early a point in this tutorial. Unless the matrix is very large it is usually not worthwhile to gener-
ate sparse matrices however, when it is worthwhile the time and storage saved can be boundless.
Section 10 discusses how to use MATLAB to numerically solve initial-value ordinary differential equa-
tions. This section is divided up into a basic part and an advanced part. It often requires very little
effort to solve even complicated odes; when it does we discuss in detail what to do and provide a num-
ber of examples. Section 11 discusses how to use MATLAB to numerically solve boundary-value ordinary
differential equations.
Section 12 discusses how to numerically handle standard polynomial calculations such as evaluating
polynomials, differentiating polynomials, and finding their zeroes. Polynomials and piecewise polynomials
can also be used to interpolate data.
Section 13 discusses how to numerically calculate zeroes, extrema, and integrals of functions.
Section 14 discusses the discrete Fourier transform and shows how it arises from the continuous Fourier
transform. We also provide an example which shows how to recover a simple signal which has been
severely corrupted by noise.
Finally, Section 15 discusses how to apply mathematical functions to matrices.
There is one appendix which collects all the commands/functions discussed in this tutorial and boxes
them up by topic. If a command/function has more than one use, it might appear in two or more boxes.
This tutorial closes with an index. It is designed to help in finding things that are just on the tip of
your tongue. All the MATLAB commands/functions discussed here are listed at the beginning of the in-
dex, followed by all the symbols, then followed by a list of all the script and function m-files which are in
the companion zip file. Only then does the alphabetical index begin (which contains all of them again).
Notation: A variable, such as x, can represent any number of types of data, but usually it represents a
scalar, a vector, or a matrix. We distinguish them by using the lowercase x when it is a scalar
or a vector, and the uppercase X when it is a matrix. Also, in MATLAB vectors can be either
row vectors, e.g., (1, 2, 3) or column vectors (1, 2, 3)T (where T is the transpose of a vector
or matrix). In a linear algebra setting we always define x to be a column vector. Thus, for ex-
ample, matrix-vector multiplication is always written as A x and the inner product of the two
vectors x and y is x 0 *y, i.e., x1 y1 + x2 y2 + + xn yn (where 0 is the MATLAB symbol
to take the transpose of a real vector or matrix).
5
1. Scalar Calculations
MATLAB can be used as a scientific calculator. To begin a MATLAB session, click on a MATLAB
icon or type matlab in a terminal and wait for the prompt, i.e., >> , to appear. (To exit MATLAB,
click on Exit MATLAB in the File menu item or type exit or quit.) You are now in the MATLAB
workspace.
You can calculate 3.17 5.7 + 17/3 by entering
>> 3.17*5.7 + 17/3
and 220 by entering
>> 2 20
And
P12
j=1 1/j can be entered as
>> 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9 + 1/10 + 1/11 + 1/12
You can enter a number in scientific notation using the operator. For example, you can enter
21020 by
>> 2*10 -20
MATLAB, however, uses e to represent 10 so that MATLAB displays
2.0000e-20
The standard way to input 21020 is as 2e-20 or 2E-20 or 2.e-20 or 2.E-20 (even
2.0000000e-00020 is acceptable).
Warning: 1020 cannot be input as e-20, but must be input as 1e-20 or 1E-20 or 1.e-20 or 1.E-20
or . . . .
MATLAB can also handle complex numbers, where i or j represents 1 . For example, 5i can be
input as 5i or as 5*i, while 51030 i can be input as 5e30i or as 5e30*i or as 5*10 30*i, but not
as 5*10 30i (which MATLAB considers to be 51030i ). To calculate (2 + 2i)4 , enter
>> (2 + 2i) 4
and MATLAB returns 64.
You can also save all of your input to MATLAB and most of the output (plots are not saved) by using
the diary command. This archive of your work can be invaluable when you are solving homework prob-
lems. You can later use an editor to extract the part you want to turn in, while burying all the false
starts and typing mistakes that occur. Conversely, if you are involved in a continuing project, this archive
can be invaluable in keeping a record of your progress.
If you do not specify a file, this archive is saved to the file diary (no extension) in the present direc-
tory. If the file already exists, this is appended to the end of the file (i.e., the file is not overwritten).
Because of this feature you can use the diary command without fear that crucial work will be overwrit-
ten.
If you are entering a line and make a mistake, there are a number of ways you can correct your error:
you can use the backspace or delete key to erase all the text back to your mistake,
you can use the left-arrow key, i.e., , and the right-arrow key, i.e., , to move back and forth
in the line, or
you can use the mouse to move back and forth in the line.
Frequently, you will want to reexecute the previous line, or another previous line. For example, you
might have made a mistake in the previous line and so it did not execute, or did not execute correctly.
Of course, you can just retype the line but, if it is very long, this can get very time-consuming. Instead,
you can use the up-arrow key, i.e., , to move backward, one statement at a time (or the down-arrow
key, i.e., to move forward). Then hit the enter (or the return) key to execute the line.
6
1.2. Variables
Arithmetical Operations
The up-arrow key moves backward in the MATLAB workspace, one line at a time.
1.2. Variables
Notation: We always use lowercase letters to denote scalar variables.
Variables can be used to store numerical values. For example, you can store the value 21/3 in the vari-
able x by entering
>> x = 2 (1/3)
This variable can then be used on the right-hand side of an equation such as
>> fx = 3*x 6 - 17*x 3 + 79
There can also be more than one statement on a line. For example, if you type
>> x = 2 (1/3); fx = 3*x 6 - 17*x 3 + 79; g = 3/fx;
then all three statements will be executed. Nothing will be printed out because semicolons follow each
statement. If you want everything printed out then type
>> x = 2 (1/3), fx = 3*x 6 - 17*x 3 + 79, g = 3/fx
Thus, you can separate statements on a line by commas or semicolons. If semicolons are used, the results
of the statement are not displayed, but if commas are used, the results appear on the computer screen.
Warning: A variable can be overwritten at will. For example, at present x = 21/3 . If you now type
>> x = x + 5
then x becomes 21/3 + 5. No warning messages are printed if a variable is overwritten, just as
in a programming language.
Although we do not discuss vectors and matrices until the next section, it is important to understand
that MATLAB considers scalar variables to be vectors of length one or matrices of size 11. For exam-
ple, if you type
>> fx
the number 57 is returned. But you can also type
>> fx(1)
or
>> fx(1,1)
and obtain the same result.
Character strings can also be stored in variables. For example, to store the string And now for some-
thing completely different in a variable, enter
>> str = 0 And now for something completely different 0
(We discuss text variables in more detail in Section 3.)
Note: To put a single quote mark into the string, use two single quote marks.
You can change a variable from a scalar to a vector or a matrix whenever you desire or whenever
you forget that the variable has already been defined. Unlike C, for example, variables do not need to be
declared (or typed). A variable springs into existence the first time it is assigned a value, and its type
depends on its context.
At start-up time, MATLAB also contains some predefined variables. Many of these are contained in the
table below. Probably the most useful of these is pi.
Warning: Be careful since you can redefine these predefined variables. For example, if you type
7
1.2. Variables
>> pi = 2
then you have redefined and no error messages will be printed out!
Another very useful predefined variable is ans, which contains the last calculated value which was not
stored in a variable. For example, it sometimes happens that you forget to put a value into a variable.
Then MATLAB sets the expression equal to the variable ans. For example, if you type
>> (3.2*17.5 - 5/3.1) 2
but then realize that you wanted to save this value, simply enter
>> x = ans
and x now contains (3.2 17.5 5/3.1)2 .
We will discuss character strings in detail in Section 3.3. For now,
>> x = 0 Silly Walks 0
puts the text Silly walks into the variable x.
In MATLAB it is trivial to display a variable: simply type it. For example, if x has the value 23.6
then
>> x
returns
x =
-23.6000
It is sometimes useful to display the value of a variable or an expression or a character string without
displaying the name of the variable or ans. This is done by using disp. For example,
>> disp(x)
>> disp(pi 3)
>> disp( 0 And now for something completely different 0 )
>> disp( 0 ------------------------------------------ 0 )
displays
-23.6000
31.0063
(Of course, you can still use End or END but you probably shouldnt.)
Variables can also be deleted by using clear. For example, to delete x type
>> clear x
Warning: This is a very dangerous command because it is so easy to lose a great deal of work.
If you mean to type
>> clear x
but instead you type
>> clear
you will delete all the variables you have created in the workspace!
8
1.3. Round-off Errors
Predefined Variables
ans The default variable name when one has not been specified.
pi .
eps Approximately the smallest positive real number on the computer such that
1 + eps 6= 1 .
Inf (as in 1/0 ). You can also type inf.
NaN Not-a-Number (as in 0/0 ). You can also type nan.
i 1 .
j 1 (the same as i because engineers often use these interchangeably).
realmin The smallest usable positive real number on the computer. This is approximately
the smallest positive real number that can be represented on the computer (on some
computer realmin/2 returns 0 ).
realmax The largest usable positive real number on the computer. This is approximately the
largest positive real number that can be represented on the computer (on most computer
2*realmax returns Inf ).
About Variables
The most important principle for you to understand about computers is the following.
Principle 1.1. Computers cannot add, subtract, multiply, or divide correctly!
Computers do integer arithmetic correctly (as long as the numbers are not too large to be stored in the
computer). However, computers cannot store most floating-point numbers (i.e., real numbers) correctly.
For example, the fraction 1/3 is equal to the real number 0.3333 . . . Since a computer cannot store this
infinite sequence of threes, the number has to be truncated.
eps is close to the difference between the exact number 1/3 and the approximation to 1/3 used in
MATLAB. 1 + eps is the smallest floating-point number after 1 which can be stored precisely in the
computer. For example, in MATLAB 1 + 0.1 is clearly greater than 1; however, on our computer
1 + 1e-40 is not. To see this, when we enter
>> (1 + .1) - 1
we obtain 0.1000 as expected.
Note: MATLAB guarantees that the expression in parentheses is evaluated first, and then 1 is subtracted
from the result.
However, when we enter
>> (1 + 1.e-40) - 1
9
1.4. Formatting Printing
MATLAB returns 0 rather than 1.e-40. The smallest positive integer n for which
>> (1 + 10 (-n)) - 1
returns 0 is computer dependent. (On our computer it is 16.) What is not computer dependent is that
this leads to errors in numerical calculations. For example, when we enter
>> n = 5; ( n (1/3) ) 3 - n
MATLAB returns -1.7764e-15 rather than the correct result of 0. If you obtain 0, try some different
values of n. You should be able to rerun the last statement executed without having to retype it by us-
ing the up-arrow key. Alternatively, on a Mac or a PC use the copy command in the menu; in Unix enter
p.
Note: It might not seem important that MATLAB does not do arithmetical operations precisely. However,
you will see in Section 5.2 that there are simple examples where this can lead to very incorrect
results.
One function which is occasionally useful when you are just playing around is the input function,
which displays a prompt on the screen and waits for you to enter some input from the keyboard. For ex-
3
ample, if you want to try some different values of n in experimenting with the expression (n1/3 ) n,
enter
>> n = input( 0 n = 0 ); ( n (1/3) ) 3 - n
The argument to the function input is the string which prompts you for input, and the input is stored in
the variable n; the semicolon keeps the result of this function from being printed out. You can easily re-
run this line for different values of n (as we described above) and explore how round-off errors can affect
simple expressions.
Note: You can input a character string in two ways:
>> str = input( 0 input string: 0 );
and then enter, for example,
0
Upper class twit of the year 0
or
>> str = input( 0 input string: 0 , 0 s 0 );
and then enter
Upper class twit of the year
The first must enter a string while the second simply enters text until the line ends.
Warning: eps and realmin are very different numbers. realmin is approximately the smallest positive
number that can be represented on the computer, whereas eps is approximately the small-
est positive number on the computer such that 1 + eps 6= 1. ( eps/realmin is larger than the
total number of atoms in the known universe.)
Request Input
input( 0 <prompt> 0 ) Displays the prompt on the screen and waits for you to input whatever is de-
sired. The optional second argument of 0 s 0 allows you to enter a string
(including spaces) without using quote marks.
10
1.5. Common Mathematical Functions
Format Options
MATLAB contains a large number of mathematical functions. Most are entered exactly as you would
write them mathematically. For example,
>> sin(3)
>> exp(2)
>> log(10)
return exactly what you would expect. As is common in programming languages, the trig functions are
evaluated in radians. However, there are corresponding functions which are evaluated in degrees.
Almost all the functions shown here are built-in functions. That is, they are coded in C so they execute
very quickly. The one exception is the factorial function, i.e., n! = 1 2 3 n, which is calculated by
>> factorial(n)
Note: This function is actually calculated by generating the vector (1, 2, . . . , n) and them multiplying all
its elements together by prod([1:n]). (We discuss the colon operator in Section 2.2.)
There is an important principle to remember about computer arithmetic in MATLAB.
Principle 1.2. If all the numbers you enter into MATLAB to do some calculation are \rea-
sonably large" and the result of this calculation is one or more numbers which are \close to"
eps , it is very likely that the number or numbers should be zero.
As an example, enter
>> deg = pi/180; th = 40; 1 - ( cos(th*deg) 2 + sin(th*deg) 2 )
The result is 1.1102e-16. Clearly, all the numbers entered into this calculation are reasonable and the
result is approximately eps. Obviously, the result is supposed to be zero since, from the Pythagorean
theorem
cos2 + sin2 = 1
for all angles . MATLAB tries to calculate the correct result, but it cannot quite. It is up to you to
interpret what MATLAB is trying to tell you.
Note: If you obtained zero for the above calculation, try
>> th = input( 0 angle = 0 ); 1 - ( cosd(th) 2 + sind(th) 2 )
for various angles. Some of these calculations should be nonzero.
There are a number of occasions in this overview where we reiterate that MATLAB cannot usually cal-
culate results exactly. Sometimes these errors are small and unimportant other times they are very
important. In fact, MATLAB has introduced two functions to reduce round-off errors. The relative error
in the calculation of ex 1, i.e., (exp(x) - 1)/exp(x) can be very large when x 1 since
x2 x3 x2 x3
x x x
e 1= 1+ + + + 1 = + + + ;
1! 2! 3! 1! 2! 3!
the term within parentheses is very close to 1 and so subtracting by 1 causes a loss of many digits in the
Be sure to define deg = pi/180 beforehand.
11
1.5. Common Mathematical Functions
so if z 1 then accuracy is lost in the calculation of z 1. This can be avoided by entering x directly
in
x x2 x3 x4
log(1 + x) = + + ,
1 2 3 4
12
1.6. Complex Numbers
13
1.7. Script M-files
Similarly,
eiz + eiz eiz eiz
cos z = and sin z = .
2 2i
14
1.8. Help!
as one of MATLAB's commands/functions. If it is, your file might not execute MAT-
LABs might! Or, you might run a MATLAB function which tries to call a function which has
the same name as yours! (The m-file it executes depends on the order in which directories are
searched for m-files see path for more details.) To check this, you can enter
>> type <file name>
before you save your m-file. This will type out the entire file if it is written in MATLAB or
type out
<file name> is a built-in function
if it is written in C or Fortran and so cannot be viewed directly. If the file name doesnt exist,
MATLAB returns
??? Undefined function or variable 0 <file name> 0 .
If MATLAB returns your m-file, it means you have already saved it. In this case enter
>> doc <file name>
(which is discussed in the next section), which returns useful information about a MATLAB
function, i.e., not one of yours. If it cannot find this particular function, you are safe.
A long expression can be continued to a new line by typing three periods followed by the enter (or
P20
return) key. For example, j=1 1/j can be entered as
>> 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9 + 1/10 + 1/11 + 1/12 + ...
1/13 + 1/14 + 1/15 + 1/16 + 1/17 + 1/18 + 1/19 + 1/20
although there are much better ways to obtain this same expression with many fewer keystrokes (as you
will see in Section 2.8). Lines can also be continued in the MATLAB workspace by using three periods,
but it is much more common to use continuation in an m-file.
If your m-file is very long, it is often valuable to include comments to explain what you are doing. Each
line of comments must begin with the percent character, i.e., %. Comments can appear alone on a line
or they can follow a statement that you have entered.
1.8. Help!
Before discussing how to obtain help in MATLAB, here is a good place to discuss a very frustrating
situation where you desperately need help: how do you abort a MATLAB statement which is presently
executing. The answer is simply to type C (that is, hold down the control key and type c).
The on-line help facility in MATLAB is quite extensive. If you type
>> help
you will get a list of all the topics that you can peruse further by typing help followed by the name of
the topic. If you want help on a specific command/function, simply type help followed by the name of
the command, i.e.,
>> help <command/function>
For example, if you forget the exact form of the format command, just type
>> help format
and you will see all the various ways that the output can be formatted.
Note: Typing
>> help ?
gives you lots of information about arithmetical and relational and logical operators and special
characters.
There is a more general command that can help you determine which commands might be of use. The
command lookfor searches through the first line of all MATLAB help entries for a particular string. It is
case insensitive so capital letters need not be used. For example,
15
1.8. Help!
These variables are saved in binary format; when loaded back in using load the variables will be exactly the
same as before. The contents of this file can be viewed by the user with an editor but the contents will appear
to be gibberish. The contents can only be interpreted by the load command.
16
2. Arrays: Vector and Matrix Calculations
Getting Help
1.9. Be Able To Do
After reading this section you should be able to do the following exercises. The solutions are given on
page 163.
1. Consider a triangle with sides a, b, and c and corresponding angles ab, ac, and bc.
(a) Use the law of cosines, i.e.,
c2 = a2 + b2 2ab cos ab ,
to calculate c if a = 3.7, b = 5.7, and ab = 79 .
(b) Then show c to its full accuracy.
(c) Use the law of sines, i.e.,
sin ab sin ac
= ,
c b
to calculate ac in degrees and show it in scientific notation.
(d) What MATLAB command should you have used first if you wanted to save these results to the file
triangle.ans?
2. Calculate 3 1.21020 1220 i.
3. Analytically, cos 2 = 2 cos2 1. Check whether this is also true numerically when using MATLAB by
using a number of different values of . Use MATLAB statements which make it as easy as possible to do
this.
4. How would you find out information about the fix function?
This makes it much easier to understand MATLAB operations. This is also a good practice
for you to use.
In addition, when we write vector we mean a column vector and so it is immediately obvious
that A*x is a legitimate operation of a matrix times a vector as long as the number of columns
of the matrix A equals the number of rows of the column vector x. Also, x*A is illegitimate
because the column vector x has only one column while the matrix A is expected to have more
than one row. On the other hand, x 0 *A is legitimate ( x 0 denotes the conjugate transpose of
the vector x ) as long as the row vector x 0 has the same number of columns as the number of
rows of the matrix A.
In addition, we have very specific notation for denoting vectors and matrices and the elements of each.
We collect all this notation here.
Notation: Rm denotes all real column vectors with m elements and Cm denotes all complex column vec-
tors with m elements.
Rmn denotes all real mn matrices (i.e., having m rows and n columns) and Cmn de-
notes all complex mn matrices.
Notation: In this overview the word vector means a column vector so that Cm = Cm1 . Vectors are de-
noted by boldface letters, such as x; we will write a row vector as, for example, xT , where T
denotes the transpose of a matrix or vector (that is, the rows and columns are reversed.)
Notation: A = (aij ) means that the (i, j)th element of A (i.e., the element in the ith row and the j th
column) is aij .
x = (xi ) means that the ith element of x is xi .
By the way MATLAB works with complex matrices as well as it does real matrices. To remind you of
this fact, we will use C rather than R unless there is a specific reason not to. If there is a distinction be-
tween the real and complex case, we will first describe the real case and then follow with the complex case
in parentheses.
in MATLAB type
>> A = [1 2 3; 4 5 6; 7 8 9]
(where denotes one or more spaces) or
>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9]
or
>> A = [1,2,3; 4,5,6; 7,8,9]
or
>> A = [ 1 , 2 , 3 ; 4 , 5 , 6 ; 7 , 8 , 9 ]
In other words, either spaces or commas can be used to delineate the elements of each row of a matrix;
semicolons are required to separate rows. (Any number of spaces can be put around commas or semicolons
to improve the readability of the expression.)
Notation: Since we prefer spaces, we will generally use them rather than commas to separate elements in a
row.
Rows can also be separated by beginning each on a separate line. For example, the matrix A can also
be entered by
>> A = [1,2,3
4,5,6
7,8,9]
However, we do not use it because there is no way to correct an element on a previous line which you have
just noticed has been entered incorrectly. The more complicated matrix
1 2+ 3 3 sin 1
C = e2 17/3
+3
1/3 2 3 7 cos /7
18
2.1. Generating Matrices
1
2
3
x = = (1, 2, 3, 4, 5, 6)T
4
5
6
can be entered as
>> x = [1; 2; 3; 4; 5; 6]
However, this requires many semicolons; instead, take the transpose of a row vector by entering
>> x = [1 2 3 4 5 6]. 0
where the MATLAB symbol for the transpose, i.e., T , is . 0 (i.e., a period followed by a single quote
mark). There is one further simplification that is usually observed when entering a vector. The MATLAB
symbol for the conjugate transpose, i.e., H , of a matrix is 0 (i.e., just a single quote mark), which
requires one less character than the symbol for the transpose. Thus, x is usually entered as
>> x = [1 2 3 4 5 6] 0
There is a simpler way to generate x, namely using the colon operator. It wont be discussed in detail for
a few pages, but in its simplest form
>> x = [1:6] 0
That is, 1:n is the same as 1, 2, 3, . . . , n.
Warning: xT x. 0 while xH x 0 so that you can only calculate xT by x 0 if x is real. This
has bitten us occasionally!
Sometimes the elements of a matrix are complicated enough that you will want to simplify the process
p p T
of generating the matrix. For example, the vector r = 2/3 , 2 , 3 , 6 , 2/3 can be entered by
typing
>> s2 = sqrt(2); s3 = sqrt(3); r = [ s2/s3 s2 s3 s2*s3 s2/s3 ] 0
or, as we will see later, by
>> r = sqrt([2/3 2 3 6 2/3]) 0
We have now discussed how to enter matrices into MATLAB by using square parentheses, i.e., [...].
19
2.1. Generating Matrices
You work with individual elements of a matrix by using round parentheses, i.e., (...). For example, the
element aij of the matrix A is A(i,j) in MATLAB. Suppose you want to create the matrix
1 2 3
B = 4 5 6
7 8 10
without having to enter all nine elements. If A (see the beginning of this section) has already been gener-
ated, the simplest way is to type
>> B = A; B(3,3) = 10;
or
>> B = A; B(3,3) = A(3,3) + 1;
That is, an element of an array
Also, the element xi of the vector x is x(i) in MATLAB. For example, to create the column vector
enter
>> x = [1:50] 0 ; x(50) = 51 % or x [1:49] 0 ; x(50) = 51
or
>> x = [1:50] 0 ; x(50) = x(50) + 1
or
>> x = [1:50] 0 ; x(length(x)) = x(length(x)) + 1
where length returns the number of elements in a vector.
MATLAB also has a number of functions that can generate matrices. For example,
>> C = zeros(5)
or
>> C = zeros(5, 5)
generates a 55 zero matrix. Also,
>> C = zeros(5, 8)
generates a 58 zero matrix. Finally, you can generate a zero matrix C with the same size as an already
existing matrix, such as A, by
>> C = zeros(size(A))
where size(A) is a row vector consisting of the number of rows and columns of A. This function is fre-
quently used to preallocate a matrix of a given size so that MATLAB does not need to guess how large
to make it.
Similarly, you can generate a matrix with all ones by ones(n) or ones(m, n) or ones(size(D)).
You can also generate the identity matrix, i.e., the matrix with ones on the main diagonal and zeroes off of
it, by using the function eye with the same arguments as above.
Another useful matrix is a random matrix, that is, a matrix whose elements are all random numbers.
The two most commonly used random numbers are uniformly distributed random numbers and normally
distributed random numbers. Uniformly distributed random numbers in [0, 1) are generated by the rand
function, which takes the same arguments as above, i.e.,
>> r = rand % or rand(1)
>> R = rand(n) % or rand(m,n)
To generate uniformly distributed random numbers in [a, b) use
>> R = a + (b - a)*rand(m, n)
To be precise, these are pseudorandom numbers because they are calculated by a deterministic formula
which begins with an initial seed which is called the state , not the seed. Every time that a new
MATLAB session is started, the default seed is set, and so the same sequence of random numbers will
be generated. However, every time that this function is executed during a session, a different sequence of
random numbers is generated. If desired, a different seed can be set at any time by entering
>> rng(<non-negative integer state number>)
To use a different sequence of random numbers every time you run MATLAB, begin your session with
>> rng( 0 shuffle 0 )
To general normally distributed random numbers with mean 0 and standard deviation 1 use
>> R = randn(m, n)
To obtain mean and standard deviation use
20
2.1. Generating Matrices
>> R = mu + sig*randn(m, n)
The normal distribution (or, at least, a reasonable approximation to it) occurs much more frequently
in the physical world than the uniform distribution. However, the uniform distribution has many uses,
including generating the normal distribution!
There are two other probability distributions which are frequently needed. Random matrices of integers
are generated by
>> r = randi(k)
which generates one integer in the interval [1, k] or
>> R = randi(k, n) % or randi(k, m, n)
which generates a matrix of integers. Similarly,
>> r = randi([k 1 k 2]) % or randi([k 1 k 2], n)
which generates one integer in the interval [k1 , k2 ].
There is another random function which is useful if you want to reorder a sequence, rather than just
generate random elements from a set. The function randperm(n) generates a random permutation of the
integers 1, 2, . . . , n. This is called a random selection without replacement.
MATLAB also makes it convenient to assemble matrices in pieces, that is, to put matrices together to
make a larger matrix. That is, the original matrices are submatrices of the final matrix. For specificity, let
us continue with A (see the beginning of this section). Suppose you want a 53 matrix whose first three
rows are the rows of A and whose last two rows are all ones. This is easily generated by
>> [ A ; ones(2, 3) ]
(The semicolon indicates that a row has been completed and so the next rows consist of all ones. The fact
that A is a matrix in its own right is immaterial. All that is necessary is that the number of columns of A
be the same as the number of columns of ones(2, 3).) This matrix could also be generated by
>> [ A ; ones(1, 3) ; ones(1, 3) ]
or by
>> [ A ; [1 1 1] ; [1 1 1] ]
or even by
>> [ A ; [1 1 1 ; 1 1 1] ]
Similarly, to generate a 34 matrix whose first three columns are the columns of A and whose last
column is (1, 5, 9)T type
>> [A [1 5 9] 0 ]
(The space following the A indicates that the next column is to follow. The fact that the next entry is
a column vector is immaterial. All that is necessary is that the number of rows of A be the same as the
number of rows in the new last column.)
21
2.2. The Colon Operator
Elementary Matrices
22
2.3. Manipulating Vectors and Matrices
1 2 3 4 5 6
7 8 9 10 11 12
E = 13 14 15 16 17 18 ,
19 20 21 22 23 24
25 26 27 28 29 30
23
2.3. Manipulating Vectors and Matrices
E(1:end,1:end) ). This is not a very useful way of entering E, but it shows how the colon operator
can work. On the other hand, entering
>> G = E( : , 6:-1:1 )
generates a matrix with the same size as E but with the columns reversed, i.e.,
6 5 4 3 2 1
12 11 10 9 8 7
G = 18 17 16 15 14 13 .
24 23 22 21 20 19
30 29 28 27 26 25
It is also very easy to switch rows in a matrix. For example, to switch the third and fifth rows of G, enter
the single line
>> G([5 3],:) = G([3 5],:)
which is much simpler, and more transparent, than the three lines
>> temp = G(3,:)
>> G(3,:) = G(5,:)
>> G(5,:) = temp
Note: There is a more general function which can reverse two variables: scalars or vector or matrices. For
example,
>> [y, x] = deal(x, y); % or [Y, X] = deal(X, Y);
reverses the values in these two variables. They can even have different sizes!
(This is a very specialized function, but it is annoying to need three statements to reverse two vari-
ables.)
Finally, there is one more use of a colon. Entering
>> f = E(:)
generates a column vector consisting of the columns of E (i.e., the first five elements of f are the first
column of E, the next five elements of f are the second column of E, etc.).
Note: On the right side of an equation, E(:) is a column vector with the elements being the columns of
E in order. On the left side of an equation, E(:) reshapes a matrix. However, we will not discuss
this reshaping further because the reshape function described below is easier to understand.
There is also a practical example for reordering the elements of a vector The random function randi can
also be used to randomly generate any set of values (integer or real or even complex) by, for example,
>> last prime = 20;
>> p = primes(last prime); % the prime numbers up to last primes
>> ir = randi(length(p), n, 1)
>> r = p(ir);
All the primes up to 20 are calculated (there are 8) and n random integers in 1, 2, 3, . . . , length(p) are
calculated. Then ir determines which primes to put into r. This is called a random selection with replace-
ment since a prime can occur more than once. If you do not want the primes to occur more than once, use
randperm instead.
The colon operator works on rows and/or columns of a matrix. A different function is needed to work
on the diagonals of a matrix. For example, you extract the main diagonal of E by typing
>> d = diag(E)
(so d is the column vector (1, 8, 15, 22, 29)T ), one above the main diagonal by typing
>> d1 = diag(E, 1)
(so d1 is the column vector (2, 9, 16, 23, 30)T ), and two below the main diagonal by typing
>> d2 = diag(E, -2)
(so d2 is the column vector (13, 20, 27)T ).
The MATLAB function diag transforms a matrix (i.e., a non-vector) into a column vector. The con-
verse also holds: when diag is applied to a vector, it generates a symmetric matrix. The function
>> F = diag(d)
generates a 55 matrix whose main diagonal elements are the elements of d, i.e., 1, 8, 15, 22, 29, and
whose off-diagonal elements are zero. Similarly, entering
>> F1 = diag(d1, 1)
generates a 66 matrix whose first diagonal elements (i.e., one above the main diagonal) are the elements
24
2.3. Manipulating Vectors and Matrices
of d1, i.e., 2, 9, 16, 23, 30, and whose other elements are zero, that is,
0 2 0 0 0 0
0 0 9 0 0 0
0 0 0 16 0 0
F1 = .
0 0 0 0 23 0
0 0 0 0 0 30
0 0 0 0 0 0
Finally, typing
>> F2 = diag(d2, -2)
generates a 55 matrix whose 2nd diagonal elements (i.e., two below the main diagonal) are the ele-
ments of d2, i.e., 13, 20, 27, and whose other elements are zero, i.e.,
0 0 0 0 0
0 0 0 0 0
F2 = 13 0 0 0 0 .
0 20 0 0 0
0 0 27 0 0
The Toeplitz matrix is a very special matrix whose values are constant along each diagonal. For exam-
ple,
7 4 3 1
2 7 4 3
5 2 7 4
1 5 2 7
is generated by
toeplitz([7 -2 -5 1], [7 4 3 1])
If the Topelitz matrix is symmetric, only the row or the column elements need be entered (i.e., only one
argument is required).
You can also extract the upper triangular or the lower triangular part of a matrix. For example,
>> G1 = triu(E)
constructs a matrix which is the same size as E and which contains the same elements as E on and above
the main diagonal; the other elements of G1 are zero. This function can also be applied to any of the
diagonals of a matrix. For example,
>> G2 = triu(E, 1)
constructs a matrix which is the same size as E and which contains the same elements as E on and above
the first diagonal, i.e.,
0 2 3 4 5 6
0 0 9 10 11 12
G2 = 0 0 0 16 17 18 .
0 0 0 0 23 24
0 0 0 0 0 30
The similar function tril extracts the lower triangular part of a matrix.
As an example of the relationship between these three functions, consider the square random matrix F
generated by
>> F = rand(6)
All the following MATLAB statements calculate F anew:
>> triu(F) + tril(F) - diag(diag(F))
>> triu(F, 1) + diag(diag(F)) + tril(F, -1)
>> triu(F) + tril(F, -1)
>> triu(F, 2) + diag(diag(F, 1), 1) + tril(F)
Note: Numerically the first statement might not generate exactly the same matrix as the following three
because of round-off errors.
It is important to note that diag , triu and tril cannot appear on the left-hand side of an
equation. Instead, to zero out all the diagonals above the main diagonal of F enter
25
2.3. Manipulating Vectors and Matrices
>> F = F - triu(F, 1)
and to zero out just the first diagonal above the main diagonal enter
>> F = F - tril(triu(F, 1), 1)
What if you want to insert numbers from the upper right-hand corner of a matrix to the lower left-hand
corner? There is no explicit function which does this but there are a number of indirect functions:
fliplr(A) flips the matrix from left to right, i.e., reverses the columns of the matrix;
flipud(A) flips the matrix up and down, i.e., reverses the rows of the matrix;
rot90(A) rot90 rotates the matrix 90 ; and
rot90(A,k) rotates the matrix k90 .
MATLAB has a function which is useful in changing the shape of a matrix while keeping the same nu-
merical values. The statement
>> K = reshape(H, m, n)
reshapes the matrix H Cpq into K Cmn where m and n must satisfy mn = pq (or an error mes-
sage will be generated). A column vector is generated from H, as in H(:), and the elements of K are
taken columnwise from this vector. That is, the first m elements of this column vector go in the first col-
umn of K, the second m elements go in the second column, etc. For example, the matrix E which has
been used throughout this subsection can be easily (and quickly) generated by
>> E = reshape([1:30], 6, 5) 0
Occasionally, there is a need to delete elements of a vector or rows or columns of a matrix. This is easily
done by using the null matrix []. For example, entering
>> x = [1 2 3 4] 0
>> x(2) = []
results in x = (1, 3, 4)T . As another example, you can delete the even columns of G by
>> G( : , 2:2:6 ) = []
The result is
6 4 2
12 10 8
G = 18 16 14 .
24 22 20
30 28 26
Also, occasionally, there is a need to replicate or tile a matrix to form a larger matrix. The statement
>> B = repmat(A, m, n)
generates a matrix B which contains m rows and n columns of copies of A. (If n = m then repmat(A,
m) is sufficient.) If A is a p by q matrix, then B Rmpnq . This even works if A is a scalar, in which
case this is the same as
>> B = A*ones(m, n)
(but it is much faster if m and n are large since no multiplication is involved).
One frequent use of repmat is when a specific operation is to be applied to each row or to each col-
umn of a matrix. For example, suppose that the column vectors { x1 , x2 , . . . , xn } have been combined
into the matrix X and we want to calculate the corresponding matrix for the vectors yj = xj + a for all
j N[1, n]. This can be easily done by
>> Y = X + repmat(a, 1, n);
which, unfortunately, requires that the new matrix A = repmat(a, 1, n) be created. We would prefer to
simply enter
>> Y = X + a (WRONG);
However, we can enter
26
2.3. Manipulating Vectors and Matrices
27
2.4. Simple Arithmetical Operations
Manipulating Matrices
A(i,j) ai,j .
A(:,j) the j th column of A.
A(i,:) the ith row of A.
A(:,:) A itself.
A(?1,?2) There are many more choices than we care to describe:
?1 can be i or i1:i2 or i1:i3:i2 or : or [i1 i2 ... ir] and
?2 can be j or j1:j2 or j1:j3:j2 or : or [j1 j2 ... jr].
A(:) On the right-hand side of an equation, this is a column vector containing
the columns of A one after the other.
diag(A) A column vector of the k th diagonal of the matrix (i.e., non-vector) A. If k
o
diag(A, k) is not given, then k = 0.
diag(d) A square matrix with the k th diagonal being the vector d. If k is not
o
diag(d, k) given, then k = 0.
triu(A) A matrix which is the same size as A and consists of the elements on and
o
triu(A, k) above the k th diagonal of A. If k is not given, then k = 0.
tril(A) The same as the function triu except it uses the elements on and below
o
tril(A, k) the k th diagonalof A. If k is not given, then k = 0.
fliplr(A) Flips a matrix left to right.
flipud(A) Flips a matrix up and down.
rot90(A) Rotates a matrix k90 . If k is not given, then k = 1.
o
rot90(A, k)
repmat(A, m, n) Generates a matrix with m rows and n columns of copies of A. (If n = m
the third argument is not needed.)
bsxfun(<fnc>, A, b) Perform the operation given by the function handle on all the columns of
the matrix A using the column vector b or on all the rows using the row
vector b
reshape(A, m, n) Generates an mn matrix whose elements are taken columnwise from A.
Note: The number of elements in A must be mn.
[] The null matrix. This is also useful for deleting elements of a vector and
rows or columns of a matrix.
toeplitz(c,r) Generates a Toeplitz matrix where the elements along each diagonal are
constant. c and r are the values on the first diagonal and the first row
respectively.
28
2.4. Simple Arithmetical Operations
29
2.4. Simple Arithmetical Operations
In linear algebra this is called the inner product and is defined for vectors a, b Rn by aT b. It is calcu-
lated by
>> a 0 *b
(If a, b Cn the inner product is aH b and is calculated by a 0 *b.) The outer product of these two vec-
tors is defined to be abT and is calculated by
>> a*b 0
(If a, b are complex the outer product is abH and is calculated by a*b 0 .) It is important to keep these
two products separate: the inner product is a scalar, i.e., aT b R (if complex, aH b C ), while the outer
product is an nn matrix, i.e., abT Rnn (if complex, abH Cnn ).
In linear algebra we often work with large matrices and are interested in the amount of work re-
quired to perform some operation. In the distant past, MATLAB kept track of the number of flops, i.e.,
the number of fl oating-pointoperations, performed during the MATLAB session. Unfortunately, this
disappeared in version 6. Instead, we can calculate the amount of CPU time required to execute a state-
ment by using cputime. This function returns the CPU time in seconds that have been used since you
began your MATLAB session. This time is frequently difficult to calculate, and is seldom more accurate
The CPU, Central Processing Unit, is the guts of the computer, that is, the hardware that executes the
instructions and operates on the data.
30
2.5. Operator Precedence
than to 1/100 -th of a second. Here is a simple example to determine the CPU time required to invert a
matrix.
>> n = input( 0 n = 0 ); time = cputime; inv(rand(n)); cputime - time
Warning: Remember that you have to subtract the CPU time used before the operation from the CPU
time used after the operation.
You can also calculate the wall clock time required for some sequence of statements by using tic and
toc . For example,
>> tic; <sequence of statements>; toc
returns the time in seconds for this sequence of statements to be performed.
Note: This is very different from using cputime. tic followed by toc is exactly the same as if you had
used a stopwatch to determine the time. Since a timesharing computer can be running many dif-
ferent processes at the same time, the elapsed time might be much greater than the CPU time. On
the other hand, on a multiprocessor computer, the elapsed time might be much less.
cputime Approximately the amount of CPU time (in seconds) used during this session.
tic, toc Returns the elapsed time between these two functions.
It is important to list the precedence for MATLAB operators. That is, if an expression uses two or more
MATLAB operators, in which order does MATLAB do the calculations? For example, what is 1:n+1? Is
it (1:n)+1 or is it 1:(n+1)? And if we solve ACx = b by A*C\b, does MATLAB do (A*C)\b or A*(C\b)?
The former is C1 A1 b while the latter is AC1 b and these are completely different. The following ta-
ble shows the precedence of all MATLAB operators, that is, the order in which it evaluates an expression.
The precedence is from highest to lowest. Operators with the same precedence are evaluated from left to
right in an expression.
31
2.6. Be Careful!
The unary plus and minus are the plus and minus signs in x = +1 and x = 1. The plus and mi-
nus signs for addition and subtraction are, for example, x = 5 + 1 and x = 10 13. Thus, 1:n+1 is
1:(n+1) because + has higher precedence than :. Also, A*C\b = (A*C)\b because * and \
have the same precedence and so the operations are evaluated from left to right.
2.6. Be Careful!
Be very careful: occasionally you might misinterpret how MATLAB displays the elements
of a vector or matrix. For example, the MATLAB function eig calculates the eigenvalues of a square
matrix. (We discuss eigenvalues in Section 7.) To calculate the eigenvalues of the Hilbert matrix of or-
der 5, i.e.,
1 1/ 1/ 1/ 1/
2 3 4 5
1/2 1/
3
1/
4
1/
5
1/
6
1/3 1/
4
1/
5
1/
6
1/
7
,
1/ 1/ 1/ 1/ 1/
4 5 6 7 8
1/ 1/ 1/ 1/ 1/
5 6 7 8 9
0.0000
0.0003
0.0114
0.2085
1.5671
You might think the the first element of this vector is 0. However, if it was zero MATLAB would display
0 and not 0.0000. Entering
>> format short e
>> ans
On the other hand, in the statistical computer languages R and S (which are somewhat similar to MATLAB),
: has higher precedence than + and so 1:n+1 is (1:n)+1 2:(n+1).
32
2.6. Be Careful!
displays
ans =
3.2879e-06
3.0590e-04
1.1407e-02
2.0853e-01
1.5671e+00
which makes it clear that the smallest eigenvalue is far from zero.
On the other hand, if you enter
>> format short
>> A = [1 2 3; 4 5 6; 7 8 9]
>> eig(A)
MATLAB displays
ans =
16.1168
-1.1168
-0.0000
It might appear from our previous discussion that the last eigenvalue is not zero, but is simply too small
to appear in this format. However, entering
>> format short e
>> ans
displays
ans =
1.6117e+01
-1.1168e+00
-8.0463e-16
Since the last eigenvalue is close to eps, but all the numbers in the matrix A are of reasonable size,
you can safely assume that this eigenvalue is zero analytically. It only appears to be nonzero when calcu-
lated by MATLAB because computers cannot add, subtract, multiply, or divide correctly!
As another example of how you might misinterpret the display of a matrix, consider the Hilbert matrix
of order two
1 1/2
H= 1 .
/2 1/3
We write H100 as
100 10 1.5437 0.8262
H 10 ,
0.8262 0.4421
while in MATLAB entering
>> format short
>> H = hilb(2)
>> H 100
displays
ans =
1.0e+10 *
1.5437 0.8262
0.8262 0.4421
It is very easy to miss the term 1.0e+10 * because it stands apart from the elements of the matrix.
Note: Use format short g so you will not have this problem.
Similarly, entering
33
2.8. Data Manipulation Functions
1.0e-15 *
0.2220 0
0 0
where, again, it is easy to miss the term 1.e-15 * and not realize that this matrix is very small in
fact, it should be zero.
Be careful: MATLAB has nite memory. You should have no problem creating a matrix by
>> A = zeros(1000)
but you might well have a problem if you enter
>> A = zeros(10000)
The amount of memory available is dependent on the computer and the operating system and is very hard
to determine. Frequently it is much larger than the amount of physical memory on your computer. But,
even if you have sufficient memory, MATLAB may slow to a crawl and become unusable. The whos com-
mand will tell you how much memory you are using and show you the size of all your variables. If you
have large matrices which are no longer needed, you can reduce their sizes by equating them to the null
matrix, i.e., [], or remove them entirely by using clear.
Warning: Recall that the clear command is very dangerous because clear A deletes the variable A
but clear (without anything following) deletes all variables!
In linear algebra mathematical functions cannot usually be applied to matrices. For example, eA and
sin A have no meaning unless A is a square matrix. (We will discuss their mathematical definitions in
Section 15.)
Here we are interested in how MATLAB applies common mathematical functions to matrices and vec-
tors. For example, you might want to take the sine of every element of the matrix A = (aij ) Cmn , i.e.,
B = (sin aij ). This is easily done in MATLAB by
>> B = sin(A)
Similarly, if you want C = (eaij ), enter
>> C = exp(A)
p
Also, if you want D = aij type
>> C = sqrt(A)
or
>> C = A. (1/2)
All the common mathematical functions in the table entitled Some Common Real Mathematical Func-
tions in Section 1.5 can be used in this way.
As we will see in the section on graphics, this new interpretation of mathematical functions makes it
easy in MATLAB to graph functions without having to use the MATLAB programming language.
MATLAB has a number of simple functions which are used quite frequently. Since many of them are
quite useful in analyzing data, we have grouped them around this common theme.
To calculate the maximum value of the vector x, type
>> m = max(x)
If you also want to know the element of the vector which contains this maximum value, type
>> [m, i] = max(x)
If the elements of the vector are all real, the result of this statement is the element which has the maxi-
mum value. However, if any of the elements of x are complex (i.e., non-real), this statement has no math-
ematical meaning. MATLAB defines it to determine the element of the vector which has the maximum
34
2.8. Data Manipulation Functions
n 1/2
1X 2
std(x) = xi h x i
n i=1
35
2.8. Data Manipulation Functions
>> sort(x)
If the vector is non-real, the elements are sorted in increasing absolute value. (If two elements have the
same absolute value, the one with the smaller absolute angle in polar coordinates is used.)
The MATLAB function diff calculates the difference between successive elements of a vector. For
example, if x Rn then the function
>> s = diff(x)
generates the vector s Rn1 which is defined by si = xi+1 xi . There are a number of uses for this
function. For example,
if s has been sorted, then if any element of diff(s) is 0, an element of s has been repeated
and we can even determine the number of times it has been repeated.
similarly, if all the elements of diff(x) are positive, then all the elements of s are monotonically
increasing.
a numerical approximation to the derivative of y = f (x) can be calculated by diff(y)./diff(x).
(The functions any and all , which are discussed in Section 8.2, are used to determine if any the elements
of a vector satisfy some property and/or if all the elements satisfy it.)
The MATLAB function which is almost the inverse of diff is cumsum. It calculates the cumula-
tive sum of the elements of a vector or matrix. For example, if s Rn1 has been generated by s =
diff(x), then
>> c = cumsum(s)
Pi
generates the vector c Rn1 where ci = j=1 sj . We can recover x by
>> xrecovered = zeros(size(x))
>> xrecovered(1) = x(1)
>> xrecovered(2:length(x)) = x(1) + c
There is also a cumulative product function, namely cumprod. Thus can be used to generate
(1, x, x2 , . . . , xn ) by
>> [1, cumprod(x*ones(1,n))]
and (1!, 2!, 3!, . . . , n!) by
>> cumprod(1:n)
All of these functions can be applied to matrices, in which case they act on each column of the matrix
separately. They can also act on each row of a matrix separately by taking the transpose of the matrix.
However, there is always an optional argument often the second, but sometimes the third which
can change the function so that it acts on each row of the matrix. The main difficulty with using another
argument is remembering if it is the second or the third!
There are also a number of MATLAB functions which are particularly designed to plot data. The func-
tions we have just discussed, such as the average and standard deviation, give a coarse measure of the
distribution of the data. To actually see what the data looks like, it has to be plotted. Two particu-
larly useful types of plots are histograms (which show the distribution of the data) and plots of data which
include error bars. These are both discussed in Section 4.1.
pAlthough it does not quite fit here, sometimes you want to know the length of a vector x, which is
x21 + x22 + x2n . (Note that this is not length(x) which returns the number of elements in x, i.e.,
n.) This length, which is often called the Euclidean length, can be calculated by entering
>> sqrt( x 0 *x )
but it can be entered more easily by
>> norm(x)
(As we discuss in Section 7, the norm of a vector is a more general concept than simply the Euclidean
length.)
Warning: The number of elements in the vector x is calculated by length(x) while the (Pythagorean)
length of the vector is calculated by norm(x).
36
2.9. Advanced Topic: Multidimensional Arrays
37
2.10. Be Able To Do
by
>> ABCD = cat(3, A, B, C, D)
which concatenates the four matrices using the third dimension of ABCD. (The 3 denotes the third di-
mension of ABCD.) And it is much easier than entering
>> ABCD(:,:,1) = A;
>> ABCD(:,:,2) = B;
>> ABCD(:,:,3) = C;
>> ABCD(:,:,4) = D;
If instead, we enter
>> ABCD = cat(j, A, B, C, D)
then the four matrices are concatenated along the j th dimension of ABCD. That is, cat(1, A, B, C, D)
is the same as [A, B, C, D] and cat(2, A, B, C, D) is the same as [A; B; C; D].
Another useful function is squeeze which squeezes out dimensions which only have one element. For
example, if we enter
>> E = ABCD(:,2,:)
(where the array ABCD was created above), then we might think that E is a matrix whose columns con-
sist of the second columns of A, B, C, and D. However, size(E) = 2 1 4 so that E is a three-
dimensional array, not a two-dimensional array. We obtain a two-dimensional array by squeeze(E).
The function permute reorders the dimensions of a matrix. For example,
>> ABCD = cat(3, A, B, C, D)
>> BCDA = permute(ABCD, [2 3 4 1])
is the same as
>> BCDA = cat(3, B, C, D, A)
That is, the second argument of permute shows where the original ordering of the dimensions, i.e., 1, 2,
. . . , n, are to be placed in the new ordering. ipermute is the inverse of permute so, for example,
>> BCDA = cat(3, B, C, D, A)
>> ABCD = ipermute( BCDA, [2 3 4 1] )
cat Concatenates arrays; this is useful for putting arrays into a higher-dimensional array.
ipermute The inverse of permute.
permute Reorders the dimensions of a multidimensional array.
squeeze Removes (i.e., squeezes out) dimensions which only have one element.
2.10. Be Able To Do
After reading this section you should be able to do the following exercises. The solutions are given on
page 163.
38
3. Anonymous Functions, Strings, and Other Data Types
4 1
1 4 1 0
1 4 1
A= . . . . . . Rnn
. . .
1 4 1
0 1 4
1 1
e1 4 1 0
e2 9 1
A= .. .. .. Rnn
. . .
en2 (n 1)2 1
0 en1 n2
(a) Enter it using as few keystrokes as possible. (In other words, dont enter the elements individually.)
(b) Zero out all the elements of A below the diagonal.
5. Enter the column vector
x = (0, 1, 4, 9, 16, 25, . . . , 841, 900)T
using as few keystrokes as possible. (In other words, dont enter the elements individually.)
6. (a) Generate a random 55 matrix R.
(b) Determine the largest value in each row of R and the element in which this value occurs.
(c) Determine the average value of all the elements of R.
(d) Generate the matrix S where every element of S is the sine of the corresponding element of R.
(e) Put the diagonal elements of R into the vector r.
7. Generate the matrix
1 2 3
A = 4 5 6 .
7 8 10
(a) Calculate a matrix B which is the square root of A. That is, B2 = A. Also, calculate a matrix C each
of whose elements is the square root of the corresponding element of A.
(b) Show that the matrices you have obtained in (a) are correct by substituting the results back into the
original formulas.
39
3.1. Anonymous Functions
here. Another reason is that there are a number of data types in MATLAB including floating-point vari-
ables, integers, text variables, cell arrays, structures, and logical variables We might as well get all these
out of the way at once.
by
>> f = @(t) t. 5 .* exp(-2*t) .* cos(3*t)
and then evaluate it by
>> x = [0:.01:1] 0
>> fx = f(x)
>> A = rand(5)
>> fA = f(A)
More generally, we can define
g(x, y, a, b, c) = xa ebx cos(cy)
by
>> g = @(x, y, a, b, c) x. a .* exp(-b.*x) .* cos(c.*y)
in which case any of the input arguments can be in R or in Rn . It is also possible although probably
not very useful to let g have one vector argument, say x = (x, y, a, b, c)T by
>> g = @(x) x(1) x(3) * exp(-x(4)*x(1)) * cos(x(5)*x(2))
(In this example there is no advantage to using .* or . .)
Warning: It is quite easy to forget to put dots (i.e., .) before the mathematical operations of multipli-
cation (i.e., * ), division (i.e., / ), and exponentiation (i.e., ). For example, if f is defined by
>> f = @(t) t 5 * exp(-2*t) * cos(3*t)
then
>> f(3)
is allowed, but not
>> f([1:10])
Be careful!
The syntax for defining an anonymous function is
>> @(<argument list>) <expression>
(Since there is no left-hand side to this expression, the name of this function is ans.) The symbol @ is the
MATLAB operator that constructs a function handle. This is similar to a pointer in C which gives the ad-
dress of a variable or of a function. The name handle is used in MATLAB to denote a variable which
refers to some object which has been created. Thus, we can think of an anonymous function as being
created by
(<argument list>) <expression>
and the handle to the function (in C, the address of the function) being returned by using @. By the way,
we can create a function handle to a MATLAB function by, for example,
>> f = @cos
so that f(3) is the same as cos(3). We give an example where this is very useful in Section 3.4
It is even possible to define a piecewise function in this way. For example, the piecewise function
1 |x| for x [1, +1]
t(x) =
0 otherwise,
40
3.2. Passing Functions as Arguments
i.e., an isosceles triangle with the length of the base 2 and the height 1, is
>> t = @(x) (heaviside(x + 1) - heaviside(x - 1)).*(1 - abs(x));
in MATLAB.
Note: The x in @(x) is a dummy variable, i.e., the x is independent of any other x which appears in
the code. Or, in other words, the function could have been defined equally well by
>> t = @(w o ) = heaviside(w o + 1) - heaviside(w o - 1).*(1 - abs(w o ));
It is important to understand that all user-defined variables which appear in <expression> must ei-
ther appear in the argument list or be defined before the function is defined. If the variable does not
appear in the argument list, then its value is xed when the function is defined. For example, if a very sim-
ple function is defined by
>> r = 10
>> h = @(x) r*x
then the function is h(x) = 10x even if r is modified later. Thus,
>> h(5)
returns 50 and so does
>> r = 0
>> h(5)
Warning: Dont forget that if a variable does not appear in the argument list, then its value is xed when
the function is defined.
A function can also be defined but don't do it by the inline function For example, the function
f defined above can also be defined by
>> f = inline( 0 t. 5 .* exp(-2*t) .* cos(3*t) 0 , 0 t 0 )
In general, if our function is
It is sometimes necessary to pass the name of a function into a MATLAB function or a function m-file
created by the user. For example, as we discuss in Section 4.1, we can plot the function y = f (x) in the
interval [5, +5] by
fplot(<function "name">, [-5 +5])
But how do we pass this name?
We put the name in quotes because we do not pass the name of the function, but its handle. If f has
been defined by an anonymous function, then we enter
41
3.3. Strings
Character strings are a very minor part of MATLAB, which is mainly designed to perform numerical
calculations. However, they perform some very useful tasks which are worth discussing now.
It is often important to combine text and numbers on a plot. Since we discuss graphics in the next sec-
tion, now is a good time to discuss how characters are stored in MATLAB variables. A string variable,
such as
>> str = 0 And now for something completely different 0
is simply a row vector with each character (actually its ASCII representation as shown on page 167) being
a single element. MATLAB knows that this is a text variable, not a regular row vector, and so converts
the numerical value in each element into the corresponding character when it is printed out. For example,
to see what is actually contained in the vector str enter
>> str + 0
or
>> 1*str
Since str is a row vector, a substring can be easily extracted. For example,
>> str(1:7)
returns And now and
>> str([9:11, 34])
returns ford.
Character variables are handled the same as vectors or matrices. For example, to generate a new text
variable which adds by Monty Python to str, i.e., to concatenate the two strings, enter
>> str2 = [str 0 - by Monty Python 0 ]
or
>> str2 = [str, 0 - by Monty Python 0 ]
(which might be easier to read). To convert a scalar variable, or even a vector or a matrix, to a character
variable use the function num2str. For example, suppose you enter
>> x = linspace(0, 2*pi, 100) 0
>> c1 = 2
>> c2 = -3
>> y = c1*sin(x) + c2*cos(x)
and want to put a description of the function into a variable. This can be done by
>> s = [ num2str(c1), 0 *sin(x) + 0 , num2str(c2), 0 *cos(x) 0 ]
without explicitly having to enter the values of c1 and c2. (An optional second argument to
num2str determines exactly how the number or numbers are to be printed, but this is usually not needed.)
A text variable can also contain more than one line if it is created as a matrix. For example,
>> Str = [ 0 And 0
0 0
now
0 0
for
0
something 0
0
completely 0
0
different 0 ]
is four lines long. Since str is a matrix, each row must have the same number of elements and so we have
to pad all but the longest row. (Using cell arrays, we will shortly show how to avoid this requirement.)
Note: We do not usually enter matrices this way, i.e., one column per line. Instead, we simply use ; to
42
3.4. Cell Arrays and Structures
separate columns. However here we need to make sure that each row has exactly the same number
of characters or else a fatal error message will be generated.
If desired, you can have more control over how data is stored in strings by using the sprintf function
which behaves very similarly to the C commands sprintf, fprintf, and printf. It is also very similar
to the fprintf function in MATLAB which is discussed in detail in Section 6. Note that the data can be
displayed directly on the screen by using disp. That is, sprintf(...) generates a character string and
disp(sprintf(...)) displays it on the screen.
There also is a str2num function to convert a text variable to a number and sscanf to do the same
with more control over how the data is read. (This is also very similar to the C command, as discussed in
Section 6.)
Occasionally, there may be a worry that a string has leading or trailing blanks. These can be removed
by
>> strtrim(<string>)
This can also be used with string matrices if there leading or trailing blanks in all the rows. (It can also
be used with cell arrays of strings, which we discuss next.)
Conversely, you can create a string with blanks in it by beginning with all blank characters and then
putting non-blanks wherever you desire by
>> n = 10;
>> str = blanks(n); >> str i = num2str( randi(1000) );
>> str(n-length(str i)+1:n) = str i;
Here some unknown integer, with unknown length, will appear at the end of the string.
0
[2.0000 + 3.0000i] go cells 0
[3x1 double] [5x5 double]
The only difference between this and a standard array is that here curly braces, i.e., {. . . }, enclose the
elements of the array rather than brackets, i.e., [. . . ]. Note that only the scalar and the text variable are
shown explicitly. The other elements are only described. A second way to generate the same cell array is
43
3.4. Cell Arrays and Structures
by
>> C(1,1) = {2+3i}
>> C(1,2) = { 0 go cells 0 }
>> C(2,1) = {[1 2 3] 0 }
>> C(2,2) = {hilb(5)}
and a third way is by
>> C{1,1} = 2+3i
>> C{1,2} = 0 go cells 0
>> C{2,1} = [1 2 3] 0
>> C{2,2} = hilb(5)
It is important to understand that there is an important difference between C(i,j) and C{i,j}. The
th
former is the cell containing element in the (i, j) location whereas the latter is the element itself. For
example,
>> C(1,1) 5 % WRONG
returns an error message because a cell cannot be raised to a power whereas
>> C{1,1} 5 % CORRECT
returns 1.2200e+02 - 5.9700e+02i. All the contents of a cell can be displayed by using the
celldisp function. In addition, just as a standard array can be preallocated by using the zeros func-
tion, a cell array can be preallocated by using the cell function. We will not discuss cells further except
to state that cell array manipulation is very similar to standard array manipulation.
Warning: In MATLAB you can change a variable from a number to a string to a matrix by simply
putting it on the left-hand side of equal signs. For example,
>> c = pi
>> c = 0 And now for something completely different 0
>> c(5,3) = 17
redefines c twice without any difficulty. However, this cannot be done with cells. If you now
try
>> c{3} = hilb(5)
MATLAB will return with the error message
??? Cell contents assignment to a non-cell array object.
In order to use c as a cell (if has been previously used as a non-cell), you have to either clear it
using clear, empty it using [], or explicitly redefine it by using the cell function.
One particularly useful feature of cell arrays is that a number of text variables can be stored in one cell
array. We previously defined a standard array of strings in Str on page 42 where each string had to
have the same length. Using a cell array we can simply enter
>> Str cell = { 0 And 0
0
now 0
0
for 0
0
something 0
0
completely 0
0
different 0 }
or
>> Str cell = { 0 And 0 ; 0 now 0 ; 0 for 0 ; something 0 ; 0 completely 0 ; 0 different 0 }
and obtain the i th row by
>> Str cell{i,:}
Note: It is even possible to sort a number of strings in lexicographical ordering by putting each string in a
separate row of a cell array and using the sort function.
Structures can store different types of data similarly to cell arrays, but the data is stored by name,
called fields , rather than by number. Structures are very similar to structures in C and C++ . The cell
array we have been using can be written as a structure by
>> Cs.scalar = 2+3i
>> Cs.text = 0 go cells 0
>> Cs.vector = [1 2 3] 0
>> Cs.matrix = hilb(5)
Typing
44
3.4. Cell Arrays and Structures
>> Cs
returns
Cs =
0
scalar 0
0
text 0
0
vector 0
0
matrix 0
and
>> isfield(Cs, 0 vector 0 )
returns 1. This is a logical function which returns true or false as a logical 1 or a logical 0. Such
functions are discussed in detail in Section 8.2.
We can also use function handles in cell elements and structures. For example, suppose you want to
work with all six basic trig functions. They can be stored in a cell array by
>> T = {@sin, @cos, @tan, @cot, @sec, @csc}
so that T{2}(0) = 1. They can also be stored in a structure by
>> Tr.a = @sin; Tr.b = @cos; Tr.c = @tan; Tr.d = @cot; Tr.e = @sec; Tr.f = @csc;
so that Tr.b(0) = 1. Incidentally, we can even store anonymous functions in cell arrays and structures.
For example,
>> C = {@sin, @(x) exp(sin(x)), @(x) exp(exp(sin(x)))}
is allowed but probably not very interesting.
Note: We cannot store function handles in standard matrices we can only store numbers.
45
3.5. Advanced Topic: Data Types and Classes
46
3.5. Advanced Topic: Data Types and Classes
Each element of C R22 has the logical value 1, i.e., true, if the corresponding element of
A is > .5 and value 0, i.e., false, otherwise. These logical values are each 1 byte.
MATLAB has 15 fundamental classes, each in the form of a matrix (from a 00 matrix up to an n
dimensional matrix for any n ). For completeness, we now list them all, separating the ones discussed in
this document with the rest.
Fundamental Classes
cell its elements can be instances of any classes and sizes
char string (each character is 2 bytes)
double double precision floating-point number (8 bytes)
function handle allows indirect references to functions
logical logical (true or false) (1 byte)
struct its fields can be instances of any classes and sizes
single single precision floating-point number (4 bytes)
int8 integer in the range 127 to 128 (1 byte)
uint8 unsigned integer in the range 0 to 255 (1 byte)
int16 integer in the range 215 + 1 to 215 (2 bytes)
uint16 unsigned integer in the range 0 to 216 1 (2 bytes)
int32 integer in the range 231 + 1 to 231 (4 bytes)
uint32 unsigned integer in the range 0 to 232 1 (4 bytes)
int64 integer in the range 263 + 1 to 263 (8 bytes)
uint64 unsigned integer in the range 0 to 264 1 (8 bytes)
For example, to obtain an instance of the single class you can enter
A = single(rand(5))
The same technique holds for all the numerical classes.
Warning: Caveat Emptor! The procedures for combining different numerical classes is very different from
other programming languages. For example, the results of
>> a = 5.5
>> i = int32(3)
>> j = int8(127)
>> ai = a + i
>> aj = a + j
are ai = 9, which is an instance of the int32 class, and aj = 127, which is an instance of
the int8 class.
To determine the class of a variable, use the function class. You can also determine if a variable has a
particular class by using isa. Continuing the previous example,
>> class(i)
returns int32 and
>> isa(i, 0 int8 0 )
returns 0.
In addition, MATLAB has user-defined classes, similar to classes in object-oriented programming lan-
guages. A simple template for generating a new class is
47
3.6. Be Able To Do
Classes
3.6. Be Able To Do
After reading this section you should be able to do the following exercises. The solutions are given on
page 163.
1. Generate a structure with the fields name, rank, and serial number. Put something appropriate in
each in two ways:
(1) directly, i.e., s.name = ???, and
(2) using the struct function.
Then add one to the serial number.
2. (a) Generate a 23 cell array with the following elements:
(1,1): a uniform random matrix of size 5.
(2,1): the string Hilbert.
(1,2): 10.
(2,2): the function handle for the function sin e x.
(1,3): this is the square of the matrix in (1, 1) .
(2,3): the logical value true.
(b) Square the value of the element (1, 2) which is in the cell element (1, 1).
48
4.1. Two-Dimensional Graphics
4. Graphics
A very useful feature of MATLAB is its ability to generate high quality two- and three-dimensional
plots using simple and flexible functions. All graphical images are generated in a graphics window,
which is completely separate from the text window in which MATLAB statements are typed. Thus,
non-graphical and graphical statements can be completely intermixed.
Graphical images can be generated both from data calculated in MATLAB and from data which has
been generated outside of MATLAB. In addition, these images can be output from MATLAB and printed
on a wide variety of output devices, including color ink-jet printers and black-and-white and color laser
printers.
There are a number of demonstrations of the graphical capabilities in MATLAB which are invoked by
>> demo
Since the MATLAB statements which generate the plots are also shown, this demo makes it quite easy
to generate your own graphics. You also can have very fine control over the appearance of the plots. We
begin by considering only the basic functions; more advanced graphics functions are discussed in the next
section.
Note: Most MATLAB functions which take vectors as arguments will accept either row or column vectors.
49
4.1. Two-Dimensional Graphics
For example,
>> plot(x, y1, 0 r 0 , x, y2, 0 g--o 0 , x, y3, 0 mp 0 )
plots three curves: the first is a red, solid line; the second is a a green, dashed line with circles at the data
points; the third has magenta pentagrams at the data points but no line connecting the points.
We can also plot the first curve, and then add the second, and then the third by
>> hold off % this is a good idea before a hold on
>> plot(x, y1)
>> hold on
>> plot(x, y2)
>> plot(xx, y3)
Note that the axes can change for every new curve. However, all the curves appear on the same plot.
(The initial hold off is always a good idea if you later use hold on.)
Warning: Do not place the hold on command before the first plot. This can lead to very strange results
statement
>> x = [0: 2*pi/(n-1): 2*pi] 0 ;
to return n 1 elements rather than n. (For example, the output of [0 : 0.01 : 0.02-eps] is 0 0.0100.)
This is why we used the statement
>> x = 2*pi*[0:n-1] 0 /(n-1);
above, which does not suffer from round-off errors because the colon operator is only applied to integers.
50
4.1. Two-Dimensional Graphics
because certain parameters have already been set. For example, entering
>> xx = linspace(0, 10, 1001);
>> hold on
>> semilogy(xx, exp(xx))
results in a linear plot, i.e., plot(xx, exp(xx)), not the semilog plot which is desired.
We briefly digress to present a technical but very important detail. If a plot is hidden (possibly
because you have been typing in the workspace and have raised the MATLAB window above the graphics
window, or because there are some other windows visible on your terminal), you may not be able to see it.
The command
>> shg
raises the current graphics window above all other windows. This is a very useful command because plots
are frequently hidden. It is particularly beneficial to put this before the first plot function in a script
M-file: it cannot do any harm, and it will make the plot visible if it is already hidden.
We also briefly digress to suggest another possible use for the plot function: making an animation. In
Section 4.6 we will discuss how to make a real movie. However, it is easy in MATLAB to simulate the
time evolution of some function by repeatedly using plot. We have just discussed how to put multiple
curves on a plot, but this rapidly becomes unwieldly. Instead, just replace one plot by another. For exam-
ple, suppose that (for some strange reason) you want to plot the periodic function
10
(x ck t)(modL) L/2 2 /w2
X
g(x, t) = ak e
k=1
for x [0, L]. This is a sum of k modes, each of which has a Gaussian shape with half-width w, where
the k th mode has amplitude ak and speed ck . The code entitled running guassians (which is con-
tained in the accompanying zip file) is
If there is no graphics window then this command is equivalent to figure, while if there is a graphics window,
then this command is equivalent to figure(gcf). We discuss figure and gcf in advanced subsections.
51
4.1. Two-Dimensional Graphics
Alternatively, you can use the pause function (discussed in Section 8.3) to make all the plots visible.
drawnow draws each new plot as fast as possible, whereas pause(time) pauses execution of the code for the given
time.
52
4.1. Two-Dimensional Graphics
53
4.1. Two-Dimensional Graphics
fplot and ezplot do not always generate exactly the same curves. For example, in
>> f = @(x) log(x) + 1;
>> fplot(f, [-2*pi 2*pi])
>> ezplot(f)
fplot generates a spurious plot for x [2, 0) where it plots the real part of log x while ezplot only
plots the function for x (0, 2]. Also, in
>> f = @(x) x ./ (x. 2 + 0.01);
>> fplot(f, [-2*pi +2*pi])
>> ezplot(f)
the vertical axes are different and ezplot is missing part of the curve. Finally, in
f = @(x) x 3/(x 2 + 3*x - 10);
ezplot(f, [-10 +10])
the function blows up at x = 5 and 2 and part of the curve for x (5, 2) is not shown.
Polar plots can also be generated by the polar function. There is also an easy function for generat-
ing polar plots, namely ezpolar.
Since you often want to label the axes and put a title on the plot, there are specific function for each of
these. Entering
>> xlabel(<string>)
>> ylabel(<string>)
>> title(<string>)
put labels on the x-axis, on the y-axis, and on top of the plot, respectively. Note that a title can contain
more than one line as was discussed in Section [Macro:[text: cell]chap].
For example, typing title(t) where
t = [ 0 The Dead 0
0
Parrot Sketch 0 ]
or
t = { 0 The Dead 0
0
Parrot Sketch 0 }
or
t = { 0 The Dead 0 ; 0 Parrot Sketch 0 }
results in a two-line title. The first uses a standard array and so requires all the rows to have the same
number of columns, whereas the latter two use a cell array and so each row can have a different length.
There are also a number of ways to plot data, in addition to the function discussed above. The two we
discuss here are histograms and error bars. To plot a histogram of the data stored in the vector x, type
>> histogram(x)
which draws a number of bins between the minimum and maximum values of the elements in x. For
example, to see how uniform the distribution of random numbers generated by rand is, type
>> x = rand(100000, 1);
>> histogram(x)
And to draw a histogram with a different number of bins, type
>> histogram(x, <number of bins>)
As another example, to see how uniform the distribution of Gaussian random numbers generated by
randn is, type
>> x = randn(100000, 1);
>> histogram(x)
which generates random numbers with mean 0 and standard deviation 1. Clearly you need more random
numbers to get a good histogram but, at the moment, we are interested in a different point. If you
rerun this function a number of times, you will find that the endpoints of the histogram fluctuate. To
avoid this instability, you can fix the endpoints of the histogram by
>> xmax = 5;
>> nrbin = 100;
>> nrdata = 1e5;
>> e = linspace(-xmax, xmax, nrbin+1);
>> x = randn(nrdata, 1);
>> histogram(x, e)
Of course, to get a good histogram you should increase nrbin, say to 500, and nrdata, say to 106 . If
54
4.1. Two-Dimensional Graphics
you now rerun this code you will see a much smoother histogram.
A histogram shows the frequency of values in a vector, say x again, but suppose we want to compare
this histogram to an actual probability density function. For example, we have just discussed the Gaussian
distribution. If it has mean and standard deviation , then the density function is
(x )2
1
f (x) = exp .
2 2 2 2
R +
where f (x) dx = 1. To generate a random sequence use
>> mu = 5;
>> sig = 2;
>> nrdata = 100000; >> x = mu + sig*randn(100000, 1);
>> histogram(x)
In order to compare the histogram with the density function, we must rescale the histogram so that its
area is 1 by
>> histogram(x, 0 Normalization 0 , 0 pdf 0 )
There are a number of other normalizations that can be used, including a cumulative probability dis-
tribution ( cdf ). It is also possible to only draw the top of the histogram by using the property name
DisplayStyle and property value stairs.
In addition, it is possible to count the number in each bin rather than plotting them by
>> nr each bin = histcounts(x, e)
or by
>> [nr each bin, e] = histcounts(x)
if you dont want to determine the edges of the bins yourself.
We have already seen how to plot the vector x vs. the vector y by using the plot function. If, addi-
tionally, you have an error bar of size ei for each point yi , you can plot the curve connecting the data
points along with the error bars by
>> errorbar(x, y, e)
Sometimes the error bars are not symmetric about the y values. In this case, you need vectors l and u
where at xi the error bars extend from yi li to yi + ui . This is done by
>> errorbar(x, y, l, u)
Note: All the elements of l and u are non-negative.
Data can also be entered into MATLAB from a separate data file. For example,
>> M = csvread( 0 <file name> 0 )
reads in data from a file one row per line of input. The numbers in each line must be separated by com-
mas. The data can then be plotted as desired. The function csvwrite writes the elements of a matrix
into a file using the same format. (If desired, you can have much more control over how data is input and
output by using the fscanf and fprintf functions, which are similar to their C counterparts. These
functions are discussed in detail in Section 6.)
The load function can also be used to read a matrix into MATLAB from a separate data file. The
data must be stored in the data file one row per line. The difference between this function and csvread
is that the numbers can be separated by commas or semicolons or by spaces. The matrix is input by
entering
>> load <file name>
or
>> load 0 <file name> 0
or
>> load( 0 <file name> 0 )
and it is stored in the matrix named <file name-no extension> (i.e., drop the extension, if any, in the
file name). Or you can enter
55
4.1. Two-Dimensional Graphics
The load function is a little tricky because it can read in files generated both by MATLAB (using the save
function) and by the user. For example,
>> save allvariables;
>> clear
or
>> save allvariables.mat;
>> clear
saves all the variables to the file allvariables.mat in binary format and then deletes all the variables. Entering
>> load allvariables
or
>> load allvariables.mat
loads all these variables back into MATLAB using the binary format. On the other hand, if you create a file, say
mymatrix.dat, containing the elements of a matrix and enter it into MATLAB using
>> load mymatrix.dat
you obtain a new matrix, called mymatrix, which contains these elements. Thus, the load function determines
how to read a file depending on the extension.
56
4.1. Two-Dimensional Graphics
Input-Output
csvread( 0 <file name> 0 ) Reads data into MATLAB from the named file, one row per line of
input; the numbers in each line must be separated by commas.
load( 0 <file name> 0 ) Reads data into MATLAB from the named file, one row per line
of input; the numbers in each line can be separated by spaces or
commas. The name of the resulting matrix is <file name>.
importdata( 0 <file name> 0 ) Similar to load but there need not be the same number of elements
in each row.
csvwrite( 0 <file name> 0 , A) Writes out the elements of a matrix to the named file using the
same format as csvread.
print Prints a plot or saves it in a file using various printer specific for-
mats.
For example, print -deps <file name> saves the plot in the file
using encapsulated PostScript (so it can be plotted on a PostScript
laser printer).
57
4.1. Two-Dimensional Graphics
Two-Dimensional Graphics
plot(x, y) Plots the data points in Cartesian coordinates. The general form
of this function is plot(x1, y1, s1, x2, y2, s2, ...) where
s1, s2, . . . are optional character strings containing information
about the type of line, mark, and color to be used.
Some additional arguments that can be used:
plot(x) plots x vs. the index number of the elements.
plot(Y) plots each column of Y vs. the index number of the ele-
ments.
plot(x,Y) plots each column of Y vs. x.
If z is complex, plot(z) plots the imaginary part of z vs. the
real part.
semilogx The same as plot but the x axis is logarithmic.
semilogy The same as plot but the y axis is logarithmic.
loglog The same as plot but both axes are logarithmic.
fplot(<function handle>, Plots the specified function within the limits given. The limits can
<limits>) be [xmin xmax] or [xmin xmax ymin ymax].
ezplot(<function handle> Generates an easy plot (similar to fplot ) given the function
)
ezplot(<fnc 1>, <fnc 2>) f (x). It can also plot a parametric function, i.e., x(t), y(t) , or
ezplot(<2D fnc>) an implicit function, i.e., f (x, y) = 0. Limits can also be specified
if desired.
polar(r, theta) Plots the data points in polar coordinates.
ezpolar(<function handle>) Generate an easy polar plot of r = < functionname >().
xlabel(<string>) Puts a label on the x-axis.
ylabel(<string>) Puts a label on the y-axis.
title(<string>) Puts a title on the top of the plot.
axis Controls the scaling and the appearance of the axes. axis equal
and axis([xmin xmax ymin ymax]) are two common uses of
this function. The endpoints of the current plot are returned by
axis (i.e., with no arguments).
xlim Sets the endpoints of the x axis.
ylim Sets the endpoints of the y axis.
hold Holds the current plot ( hold on ) or release the current plot
( hold off ).
linspace(a, b, n) Generates n equally-spaced points between a and b (inclusive).
logspace(a, b, n) Generates n logarithmically spaced points between 10a and 10b .
histcounts Returns the number in each bin
histogram(x) Plots a histogram of the data in a vector using an appropriate
number of bins.
hist(x, <number of bins>) changes the number of bins.
hist(x, e) lets you choose the endpoints of the bins.
errorbar(x, y, e) The first plots the data points x vs. y with error bars given by e.
o
errorbar(x, y, l, u) The second plots error bars which need not be symmetric about y.
subplot(m, n, p) Divides the graphics window into mn rectangles and selects
the pth rectangle for the current plot. In addition, rectangles can
be placed anywhere inside the window by subplot( 0 Position 0 ,
...).
shg Raises the current graphics window so that it is visible, or creates
a new graphics window if none exists.
drawnow Update the current figure (which is frequently not done if MAT-
LAB is executing further statements).
58
4.2. Three-Dimensional Graphics
The MATLAB function plot3 plots curves in three-dimensions. For example, to generate a helix enter
>> t = linspace(0, 20*pi, 1001);
>> c = cos(t);
>> s = sin(t);
>> plot3(c, s, t)
and to generate a conical helix enter
>> t = linspace(0, 20*pi, 2001);
>> c = cos(t);
>> s = sin(t);
>> plot3(t.*c, t.*s, t)
Also, you can put a label on the z-axis by
>> zlabel(<string>)
There is also an easy plot3 function. It generates the curve x(t), y(t), z(t) for t (0, 2) by
>> ezplot3(x, y, z)
if x, y, and z have been defined using anonymous functions. Again, you change the domain of t by
specifying the additional argument [tmin, tmax].
MATLAB also plots surfaces z = f(x, y) in three-dimensions with the hidden surfaces removed. First,
the underlying mesh must be created. The easiest way is to use the function meshgrid. This combines a
discretization of
the x axis,
i.e., { x1 , x2 , . . . , xm }, and the y axis, i.e., { y1 , y2 , . . . , yn }, into the rect-
angular mesh (xi , yj ) i = 1, 2, . . . , m , j = 1, 2, . . . , n in the xy plane. The function f can then be
evaluated at these mesh nodes. For example,
>> x = linspace(-3, 3, 61) 0 ;
>> y = linspace(-2, 2, 41) 0 ;
>> [X, Y] = meshgrid(x, y);
>> F = (X + Y).*exp( -X.*X - 2*Y.*Y );
>> mesh(X, Y, F)
generates a colored, wire-frame surface whereas
>> surf(X, Y, F)
generates a colored, filled-in surface. We discuss how to change the colors, and even how to use the colors
as another variable, in the next section.
You can change the view of a three-dimensional plot by clicking on the menu item which shows a coun-
terclockwise rotation. Then put the mouse in the plot, hold down the left button, and begin moving it.
You can also change it by using the view function, which can be called in either of two ways:
First, you can give the angles from the origin of the plot to your eye by
view(<azimuth>, <elevation>)
where the azimuth is the angle in degrees in the xy plane measured from the y axis (so 0 is the
y axis, 90 is the x axis, 180 is the y axis, etc.) and the elevation is the angle in degrees up
from the xy plane toward the +z axis (so 0 is in the xy plane, 90 is on the +z axis, etc.).
Second, you can give the coordinates of a vector pointing from the origin of the plot to your eye by
view([x y z]), where you enter the coordinates of the vector.
If you type
>> contour(X, Y, F)
you will see contour plots of the surface. That is, you will be looking down the z axis at curves which
represent lines of constant elevation (i.e., constant z values). If we type
>> contour3(X, Y, F)
you will see contour plots of the surface in three dimensions. You can again change your view of these
curves by using the view function. These contour lines are labelled by
>> [C, h] = contour(X, Y, F)
>> clabel(C, h)
Also, contour lines are plotted at specific values by
>> contour(X, Y, F, v)
where v is a vector of the values. To obtain a filled contour plot enter
>> contourf(X, Y, F)
If you do not want to bother with generating the mesh explicitly, you can generate easy plots by
59
4.2. Three-Dimensional Graphics
r + e2r sin 2
f (r, ) = for r 1
1.2 r cos 3
is
>> f = @(r, th) ( r + exp(2*r.*sin(2*th)) ) ./ ( 1.2 - r.*cos(3*th) );
>> r = linspace(0, 1, 51);
>> th = linspace(0, 2*pi, 61);
>> [R, Th] = meshgrid(r, th);
>> [X, Y] = pol2cart(Th, R);
>> surf(X, Y, f(R, Th))
The function pol2cart transforms the polar coordinates into cartesian coordinates which can be under-
stood by surf, mesh, or contour.
We close with an additional detail about meshgrid. It can also generate a grid in three dimensions by,
for example,
>> x = linspace(-3, 3, 61) 0 ;
>> y = linspace(-2, 2, 41) 0 ;
>> z = linspace(0, 1, 11) 0 ;
>> [X, Y, Z] = meshgrid(x, y, z);
Three dimensions is the hightest we can go with meshgrid. However, a multidimensional grid can also be
generated by
>> [X, Y, Z] = ndgrid(x, y, z);
and ndgrid can be used in any number of dimensions. The difference between the two functions is that
the order of the first two arguments is reversed. For example,
>> [X, Y] = meshgrid(1:3, 4:7)
returns
1 2 3 4 4 4
1 2 3 5 5 5
X= , Y=
1 2 3 6 6 6
1 2 3 7 7 7
while
>> [X, Y] = ndgrid(1:3, 4:7)
returns
1 1 1 1 4 5 6 7
X = 2 2 2 2 , Y = 4 5 6 7
3 3 3 3 4 5 6 7
60
4.3. Advanced Topic: Functions
Three-Dimensional Graphics
plot3(x, y, z) Plots the data points in Cartesian coordinates. The general form of this
function is plot(x1, y1, z1, s1, x2, y2, z2, s2, ...) where s1,
s2, . . . are optional character strings containing information about the
type of line, mark, and color to be used.
ezplot3(<fnc 1>, Generates an easy plot in 3-D.
<fnc 2>, <fnc 3>)
mesh(X, Y, Z) Plots a 3-D surface using a wire mesh.
ezmesh(<2D fnc>) Generates an easy 3-D surface using a wire mesh.
surf(X, Y, Z) Plots a 3-D filled-in surface.
ezsurf(<2D fnc>) Generates an easy 3-D filled-in surface.
view Changes the viewpoint of a 3-D surface plot by
view(<azimuth>, <elevation>) or view([x y z]).
meshgrid(x, y) Generates a 2-D grid given the x-coordinates and the y-coordinates of the
mesh lines.
ndgrid(x, y) Same as meshgrid except that the two arguments are reversed.
pol2cart(Th, R) convert polar to cartesian coordinates.
zlabel(<string>) Puts a label on the z-axis.
axis Controls the scaling and the appearance of the axes.
axis([xmin xmax ymin ymax zmin zmax]) changes the endpoints of the
axes.
contour(X, Y, Z) Plots a contour looking down the z axis.
contourf(X, Y, Z) Plots a filled contour.
ezcontour(<2D fnc>) Generates an easy contour looking down the z axis.
contour3(X, Y, Z) Plots a contour in 3-D.
ezcontour3(<2D fnc>) Generates an easy contour in 3-D.
clabel Label contour lines generated by contour or contour3.
subplot(m, n, p) Remember than subplot can also be called in 3-D to put a number of
plots in one graphics window.
61
4.3. Advanced Topic: Functions
On a Macintosh computer you probably do not have a center mouse button.
62
4.3. Advanced Topic: Functions
63
4.3. Advanced Topic: Functions
64
4.3. Advanced Topic: Functions
MATLAB can also plot a two-dimensional image (i.e., a picture) which is represented by a matrix
X Rmn . The (i, j)th element of X specifies the color to use in the current color map. This color ap-
pear in the (i, j)th rectilinear patch in the plot. For example, to display the color image of a clown enter
>> load clown
>> image(X);
>> colormap(map)
The image function inputs the matrix X and the colormap map from clown.mat. Then the image is
displayed using the new color map. Similarly,
>> load earth
>> image(X);
>> colormap(map);
>> axis image
displays an image of the earth. (The axis function forces the earth to be round, rather than elliptical.)
(In the demonstration program, after clicking on Visualization double-click on Image colormaps to see
the images which you can access in MATLAB and the existing color maps.)
Incidentally, imagesc is a similar function, but with one important difference. They both use the same
colormap, i.e., the current colormap, but the matrix A Rmn , which should have integer elements, has a
different meaning. In
>> image(C)
each element of C, say cij , corresponds to this entry in the colormap, and let it have ` colors, i.e., it
is a R`3 matrix. If cij < 1 or cij > `, this function treats them as if cij = 1 or cij = `, respectively.
However,
>> imagesc(C)
first determines the minimum element m1 and the maximum element m2 in C. The minimum value is
scaled linearly to the first color in the colormap, and the maximum value to the last color.
Incidentally, many grayscale or color images can be imported into MATLAB by
>> X = imread(<filename>);
or
>> [X, map] = imread(<filename>);
where map is the associated colormap for the image. The types of files which can be imported are: bmp,
cur, fts, fits, gif, hdf, ico, j2c, j2k, jpf, jpx, jpg, jpeg, pmb, pcx,
pgm, png, pnm, pps, ras, tif, tiff, or wxd. They can be shown by image or imshow.
They can be exported by imwrite.
65
4.4. Advanced Topic: Handles and Properties
caxis([v min, v max]) Change the scaling used in the color map so that the value of
v min corresponds to the first row of the colormap and v max to the
last row. Values outside this interval map to the closest endpoint.
clf Clear a figure (i.e., delete everything in the figure)
colorbar Adds a color bar showing the correspondence between the value and
the color.
colormap Determines the current color map or choose a new one.
demo Runs demonstrations of many of the capabilities of MATLAB.
figure Creates a new graphics window and makes it the current target.
figure(n) makes the nth graphics window the current target.
fill(x, y, <color>) Fills one or more polygons with the color or colors specified by the
vector or string <color>.
fill3(x, y, z, <color>) Fills one or more 3D polygons with the color or colors specified by the
vector or string <color>.
image Plots a two-dimensional matrix.
imagesc Plots a two-dimensional matrix and scales the colors
imread Import an image from a graphics file.
imshow Display an image.
imwrite Export an image to a graphics file.
In this subsection we briefly discuss handle graphics. This is a collection of low-level graphics functions
which do the actual work of generating graphics. In the previous parts of this section we have mainly
discussed high-level graphics functions which allow us to create useful and high quality graphical im-
ages very easily. The low-level functions allow us to customize these graphical images, but at the cost of
having to get much more involved in how graphical images are actually created. This subsection will be
quite short because we do not want to get bogged down in this complicated subject. Instead, we will only
discuss a few of what we consider to be the more useful customizations.
In handle graphics we consider every component of a graphical image to be an object, such as a subplot,
an axis, a piece of text, a line, a surface, etc. Each object has properties and we customize an object by
changing its properties. Of course, we have to be able to refer to a particular object to change its prop-
erties, and a handle is the unique identifier which refers to a particular object. (Each handle is a unique
floating-point number.)
We will use a small number of examples to explain handle graphics. There are many properties of the
text that can be changed in the text function by
>> text(xpt, ypt, <string>, 0 <Prop 1> 0 , <Value 1>, 0 <Prop 2> 0 , <Value 2>, . . . )
or
>> h = text(xpt, ypt, <string>);
>> set(h, 0 <Prop 1> 0 , <Value 1>, 0 <Prop 2> 0 , <Value 2>, . . . )
where <Prop ?> is the name of one of the properties for the text object and <Value ?> is one of the
66
4.4. Advanced Topic: Handles and Properties
allowed values. (We show some names and values in the following table.) We have shown two ways to cus-
tomize the properties. In the former all the properties are set in the text function. In the latter the text
function creates an object, using its default properties, with handle h. The set function then changes
some of the properties of the object whose handle is h. For example, entering
>> set(h, 0 Color 0 , 0 r 0 , 0 FontSize 0 , 16, 0 Rotation 0 , 90)
results in a large, red text which is rotated 90 . You can also change the default properties for gtext,
xlabel, ylabel, zlabel, and title.
Text Properties
Clipping on (default) Any portion of the text that extends outside the axes rect-
angle is clipped
off No clipping is done.
Color A three-element vector specifying a color in terms of its red, blue, and
green components, or a string of the predefined colors.
FontName The name of the font to use. (The default is Helvetica.)
FontSize The font point size. (The default is 10 point.)
HorizontalAlignment left (default) Text is left-justified
center Text is centered.
right Text is right justified.
Rotation The text orientation. The property value is the angle in degrees.
VerticalAlignment top The top of the text rectangle is at the point.
cap The top of a capital letter is at the point.
center (default) The text is centered vertically at the point.
baseline The baseline of the text is placed at the point.
bottom The bottom of the text rectangle is placed at the point.
The more common way of customizing parameters is by using the set function. The two functions get
and set are used to obtain the value of one parameter and to set one or more parameters. For example,
to get the font which is presenting being used enter
>> s = get(h, 0 FontName 0 )
and the string s now contains the name of the font. The two arguments to get are the handle of the
object desired and the name of the property.
There are two other functions which can obtain a handle:
>> hf = gcf
returns the handle of the current figure and
>> ha = gca
returns the handle of the current axes in the current figure. For a simple example which uses handle
graphics, suppose we want to plot the function y = esin x for x [0, 2] and we want the horizontal axis
to have major tick marks at every /2 and we want these tick marks labelled. We do this by
>> x = linspace(0,2*pi,101);
>> plot(x,exp(sin(x)))
>> set(gca, 0 XTick 0 , [0:pi/2:2*pi])
>> set(gca, 0 XTickLabel 0 , { 0 0 0 , 0 .5*pi 0 , 0 pi 0 , 0 1.5*pi 0 , 0 2*pi 0 })
>> set(gca, 0 XMinorTick 0 , 0 on 0 )
>> set(gca, 0 TickDir 0 , 0 out 0 )
where the third line puts major tick marks at multiples of /2, the fourth line puts the labels shown
at each tick mark, the fifth line adds small tick marks between the labelled ticks, and the last line puts
the tick marks outside the plot boxed area. (At present, we cannot use TEXcharacters in XTickLabel to
generate a Greek .)
There is one case where we frequently use handle graphics. When a figure is printed, the graphical im-
ages do not fill the entire page. The default size is approximately 6.5 inches wide and 5.5 inches high.
When we want to use the full size of a sheet of paper we use
>> figure( 0 PositionPaper 0 , [0 0 8.5 11])
67
4.5. Advanced Topic: GUIs (Graphical User Interfaces)
or
>> figure(n)
>> set(gcf, 0 PositionPaper 0 , [0 0 8.5 11])
since the default units for this property are inches. This sets the graphical images to use the full paper
size (the position is given as [left bottom width height] ) with a one inch border. This is frequently
useful if subplot is being used to put a number of plots on a page.
Finally, if subplot is being used, it is sometimes useful to put a title on the entire page, not just in
each subplot. This can be done by
>> axes handle = axes( 0 Position 0 , [0 0 1 0.95], 0 Visible 0 , 0 off 0 );
>> title handle = get(axes handle, 0 Title 0 );
>> set(title handle, 0 String 0 , <title>, 0 Visible 0 , 0 on 0 );
The first line specifies a rectangle for the axes in normalized units (so that
[left bottom width height] = [0 0 1 1] is the full size of the figure). The axes are invisible because
they are only being created so that a title can go on top. The second line gets the handle for the title
object of the new axes. The third line puts <title> into the title object and makes it visible.
get(<handle>, 0 <Prop> 0 ) Return the current value of the property of the object with this
handle. Note: Case is unimportant for property names.
set(<handle>, 0 <Prop 1> 0 , Set the property, or properties, of the object with this handle. Note:
<Value 1>, ...) Case is unimportant for property names.
gca The current axes handle.
gcf The current figure handle.
68
4.5. Advanced Topic: GUIs (Graphical User Interfaces)
name. You have created two files, the fig file (i.e., the extension is fig) and the function file (i.e., the
extension is m). So far you have only created the first two elements of a GUI: the components and the fig-
ure. The third part, i.e., the callbacks, are your responsibility. Your program must be integrated into this
function file and you must also write the code to connect an event with its effect on your now integrated
program.
We will not discuss guide any further, and we will not discuss how to integrate your program and
code the callbacks. This is well-documented in MATLAB, including an explicit example which is called
simple gui. Read this documentation carefully and work through this explicit example yourself.
What we will discuss is how to use the non-simple way to write a GUI, namely by writing all the actual
functions which setup the figure, the components, and the callbacks. Since this can get quite complicated,
we only show two very simple examples. We will not write any GUIs from scratch. Instead, we will show
how to take a simple figure which is created by the plot function and add something to it. Thus, we
will not attempt to describe all the functions which are involved in generating a GUI, but only a very
small subset.
For the first example consider the function
function rippling(a, b)
n = 101;
x = linspace(-2, 2, n);
y = x;
[X, Y] = meshgrid(x, y);
for t = 0:.01:10
at = a + .8*t;
bt = b + .4*t;
Yxy = Y + .25*sin(2*(exp(X/2)-1));
Z = sin((at + .1*X + .2*Yxy).*X. 2 + ...
bt*(sin(2*Yxy) + .2*Yxy).* Yxy. 2);
surf(X, Y, Z);
view([-45, 60])
xlabel( 0 x 0 )
ylabel( 0 y 0 )
zlabel( 0 z 0 )
title(t)
drawnow
end
z = f (x, y, t; a, b) = sin [(a + 0.8t) + 0.1x + 0.2(y)]x2 + (b + 0.4t)[sin 2(y) + 0.2(y)] 2 (y)
where
(y) = y + 0.25 sin 2(ex/2 1) .
It is rippling in time (and the time is shown at the top of the 3D surface). Suppose we would like to
stop the time evolution briefly to admire the surface. This is easily done by
69
4.5. Advanced Topic: GUIs (Graphical User Interfaces)
The actual figure is shown below when the push button has been clicked.
The discussion of this code follows. shg either raises the current already-existing figure, or creates a
new figure. The uicontrol function (user interface control) positions a component (check box, editable
text field, list box, pop-up menu, push button, radio button, slider, toggle buttons, or static text field) in
the figure. This component must be attached to something, which is called its parent. (uipanel can be
used to split the GUI into different regions; a uicontrol can then be attached to any of these panels or
the original figure.) The first argument to the uicontrol function in the code determines its parent. (It
is not actually needed because the default parent is the current figure, but it never hurts.) The remain-
ing arguments occur in pairs with the first being the property name and the second its value (which might
be a string or a scalar or a matrix or a structure or a figure handle or a . . . ). The first pair of arguments
makes this control a push button, the second that the word Pause should appear on the button, the third
that the units are pixels, and the fourth the position of the button in the figure (using these units). The
button is to be positioned beginning at the lower left hand corner of the figure and extend 80 pixels to the
right and 20 pixels upward. However, the push button still does not do anything. The last pair of argu-
ments makes the event of pushing a button execute the function button. The next line in the code runs
the function rippling (which has been discussed previously) using the parameters a = b = 0.
As long as the user does not click the push button, everything is as if rippling was run directly from
the workspace. Clicking the push button (i.e., triggering an event) causes the function button to be ex-
ecuted where the first argument hObject is a handle to the particular event. (The second argument is
unused.) get returns the value of the property name String which is attached to the handle hObject.
This value is the string Pause and so the if statement is true. The function set is executed and it re-
places the push button label by Continue. uiwait then blocks execution of the program (i.e., plotting
the surface). The program is now in a wait state and will remain there until the user clicks the push but-
ton (whose label is now Continue) again. button is again executed and now the if statement is false
because str contains Continue. uiresume is executed so the program resumes execution. The following
set function changes the label on the push button back to Pause.
The above GUI does not allow us to modify a or b. The following one does.
The button could have been positioned in a more pleasing location in the GUI because there is lots of avail
space in a three-dimensional plot. However, in a two-dimensional plot this is a safe location.
70
4.5. Advanced Topic: GUIs (Graphical User Interfaces)
71
4.5. Advanced Topic: GUIs (Graphical User Interfaces)
72
4.5. Advanced Topic: GUIs (Graphical User Interfaces)
73
4.6. Advanced Topic: Making Movies
GUI
guide Invoke the GUI design environment to design your own GUI.
uicontrol(<handle>, 0 <Prop 1> 0 , Create a user interface component. The various compo-
<Value 1>, ...) nents are: check boxes, editable text fields, list boxes, pop-up
menus push buttons, radio buttons, sliders, static text labels,
toggle buttons. The first argument (which is optional) is the
handle of the parent (default is gcf). Some of the proper-
ties are: BackgroundColor, Callback, FontSize, FontUnits,
ForegroundColor, Max (maximum value, but only used by
some components), Min (minimum value, but only used by
some components), Parent (instead of using the first argu-
ment), Position, SliderStep (only used by some components),
String, Style (which component), Units, UserData (user spec-
ified data), Value (current value of component, but only used
by some components), and Visible (whether the component
should be currently visible).
Note: Case is unimportant for property names.
uipanel(<handle>, 0 <Prop 1> 0 , Create a user interface panel. This is used to subdivide the
<Value 1>, ...) GUI if desired. It is useful if different parts of the GUI cor-
respond to different tasks and so components are attached to
panels which are then attached to the figure.
uiwait Block execution of the GUI.
uiresume Resume execution of the GUI.
There are a number of different ways to make movies in MATLAB. We show some of them in the fol-
lowing code which is a modification of the MATLAB function life (which is copyrighted by The Math-
Works, Inc). The documentation inside life follows.
LIFE MATLABs version of Conways Game of Life.
Life is a cellular automaton invented by John Conway that involves live and dead cells in a
rectangular, two-dimensional universe. In MATLAB, the universe is a sparse matrix that is
initially all zero.
Whether cells stay alive, die, or generate new cells depends upon how many of
their eight possible neighbors are alive. By using sparse matrices, the calculations required
become astonishingly simple. We use periodic (torus) boundary conditions at the edges of the
universe. Pressing the Start button automatically seeds this universe with several small
random communities. Some will succeed and some will fail.
74
4.6. Advanced Topic: Making Movies
75
4.6. Advanced Topic: Making Movies
Movies
76
5.1. Square Linear Systems
4.7. Be Able To Do
After reading this section you should be able to do the following exercises. The solutions are given on
page 163.
1. Plot ex and one of its Taylor series approximations.
(a) Begin by plotting ex for x [1, +1].
(b) Then plot
x x2 x3
p3 (x) = 1 + + +
1! 2! 3!
on the same graph.
(c) Also plot the difference between ex and this cubic polynomial, i.e., ex p3 (x) on the same graph.
(d) Next, generate a new graph containing all three curves by using only one plot function, force the
axes to be to the same scale, and let all three curves have different colors. Put labels on the x and y
axes and a silly title on the entire plot.
(e) The above plot is not very instructive because ex p3 (x) is much smaller than either ex or p3 (x).
Instead, use two plots. The first plot contains ex and p3 (x) and the second plot, which is immediately
below the first, contains ex p3 (x). These two plots should fill an entire sheet of paper.
2. Consider the function
f (x, y) = (x2 + 4y 2 ) sin(2x) sin(2y) .
77
5.1. Square Linear Systems
>> x = linsolve(A, b)
The advantage of using linsolve is that it can be much faster when A has a particular property. The
third argument to linsolve gives the particular property. For our purposes the most important proper-
ties are lower triangular, upper triangular, symmetric, and positive definite. Enter
>> x = linspace(A, b, prop)
where prop is a logical structure with the following elements:
LT the matrix is lower triangular,
UT the matrix is upper triangular,
SYM the matrix is symmetric triangular, and
POSDEF the matrix is positive definite.
Normally, all the elements are false; set the property you want to true by
>> prop.??? = true
where ??? is one of the above properties. To turn this property back off, enter
>> prop.??? = false
(We discuss logical variables in Section 8.1.) If A has one (or more) of these properties, it can be solved
much faster than using x = A\b.
When A is singular there are either zero solutions or an infinite number of solutions to this equation
and a different approach is needed. The appropriate MATLAB function is now rref. It begins by ap-
plying Gaussian elimination to the linear system of equations. However, it doesnt stop there; it continues
until it has zeroed out all the elements it can, both above the main diagonal as well as below it. When
done, the linear system is in reduced row echelon form:
The first nonzero coefficient in each linear equation is a 1 (but a linear equation can be simply
0 = 0, in which case it has no nonzero coefficient).
The first nonzero term in a particular linear equation occurs later than in any previous equation.
That is, if the first nonzero term in the j th equation is xkj and in the (j+1)st equation is xkj+1 ,
then kj+1 > kj .
To use rref, the linear system must be written in augmented matrix form, i.e.,
x1 x2 xn = rhs
a11 a12 ... a1n b1
a
21 a22 ... a2n b2
... .. .. . .. .
. . .. .
am1 am2 ... amn bm
Warning: It is very important to understand that an augmented matrix is not a matrix (be-
cause the operations we apply to augmented matrices are not the operations we apply to ma-
trices). It is simply a linear system of equations written in shorthand: the first column is the
coefficients of the x1 term, the second column is the coefficients of the x2 term, etc., and the
last column is the coefficients on the right-hand side. The vertical line between the last two
columns represents the equal sign. Normally, an augmented matrix is written without explicitly
writing the header information; however, the vertical line representing the equal sign should be
included to explicitly indicate that this is an augmented matrix.
rref operates on this augmented matrix to make as many of the elements as possible zero by using al-
lowed operations on linear equations these operations are not allowed on matrices, but only on linear
systems of equations. The result is an augmented matrix which, when written back out as a linear system
of equations, is particularly easy to solve. For example, consider the system of equations
x1 + 2x2 + 3x3 = 1
4x1 + 5x2 + 6x3 = 1
7x1 + 8x2 + 10x3 = 0 ,
78
5.1. Square Linear Systems
x1 x2 x3 = rhs
1 2 3 1
4 5 6 1 .
7 8 10 0
(We have included the header information for the last time.) Entering
>> rref([A b])
returns the augmented matrix
1 0 0 2
0 1 0 3 .
0 0 1 1
Clearly, the solution of the linear system is x1 = 2, x2 = 3, and x3 = 1.
Of course, you could just as easily have found the solution by
>> x = A\b
so let us now consider the slightly different linear system
x1 + 2x2 + 3x3 = 1
4x1 + 5x2 + 6x3 = 1
7x1 + 6x2 + 9x3 = 1 ,
Since A is a singular matrix, the linear system has either no solutions or an infinite number of solutions.
The augmented matrix for this linear system is
1 2 3 1
4 5 6 1 .
7 8 9 0
Entering
>> rref([A b])
returns the augmented matrix
1 0 1 1
0 1 2 1 ,
0 0 0 0
so the solution of the linear system is x1 = 1 + x3 and x2 = 1 2x3 for any x3 R (or C if desired).
In vector form, the solution is
x1 1 + x3 1 x3 1 1
x2 = 1 2x3 = 1 + 2x3 = 1 + x3 2 .
x3 x3 0 x3 0 1
Suppose you modify the matrix equation slightly by letting b = (1, 1, 0)T . Now entering
>> rref([A b])
results in the augmented matrix
1 0 1 1
0 1 2 1 .
0 0 0 1
79
5.2. Catastrophic Round-Off Errors
Since the third equation is 0 = 1, there is clearly no solution to the linear system.
Warning: The function rref does not always give correct results. For example, if
0.95 0.03
C=
0.05 0.97
then the matrix I C is singular (where I is the identity matrix). However, if you solve
(I C)x = 0 by
>> C = [0.95 0.03; 0.05 0.97];
>> rref([eye(size(C))-C, [0 0] 0 ])
MATLAB displays
ans =
1 0 0
0 1 0
which indicates that the only solution is x = 0. On the other hand, if you enter
>> C = [0.95 0.03; 0.05 0.97]; b = 1;
>> rref([eye(size(C))-C [b 0] 0 ])
then MATLAB realizes that I C is singular. Clearly there is some value of b between 0
and 1 where MATLAB switches between believing that I C is non-singular and singular.
linsolve(A, b, <properties>) Solve the linear system of equations Ax = b where A has certain
properties.
rref Calculates the reduced row echelon form of a matrix or an aug-
mented matrix.
80
5.3. Overdetermined and Underdetermined Linear Systems
observe that the result displayed is nowhere close to the zero matrix! However, note that MATLAB is
warning you that it thinks something is wrong with the statement
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.541976e-18.
( RCOND is its estimate of the inverse of the condition number. See cond in Section 7 for more details.)
Now choose some small nonzero values for and see what happens. How small can be before MAT-
LAB warns you that the matrix is close to singular or badly scaled? In this example, you know that the
matrix is close to singular if is small (but nonzero) even if MATLAB does not. The next example is
more interesting.
For the second example, consider the Hilbert matrix of order n, i.e.,
1 1/2 1/3 . . . 1/n
1/2 1/3 1/4 . . . 1/(n + 1)
1/3 1/4 1/5 . . . 1/(n + 2) ,
Hn =
.. .. .. . . ..
. . . . .
1/n 1/(n + 1) 1/(n + 2) . . . 1/(2n 1)
which is generated in MATLAB by
>> H = hilb(n)
There does not seem to be anything particularly interesting, or strange, about this matrix; after all,
hij = 1/(i + j 1) so the elements are all of reasonable size. If you type
>> n = 10; H = hilb(n); ( H (1/2) ) 2 - H
the result is not particularly surprising. (Recall that H (1/2) is very different from H. (1/2).) The
resulting matrix should be the zero matrix, but, because of round-off errors, it is not. However, every
element is in magnitude less than 1015 , so everything looks fine.
However, suppose you solve the matrix equation
Hx = b
for a given b. How close is the numerical solution to the exact solution? Of course, the problem is: how
can you know what the analytical solution is for a given b? The answer is to begin with x and calcu-
late b by b = Hx. Then solve Hx = b for x and compare the final and initial values of x. Do this in
MATLAB by
>> n = 10; x = rand(n, 1); b = H*x; xnum = H\b
and compare x with xnum by calculating their difference, i.e.,
>> x - xnum
The result is not very satisfactory: the maximum difference in the elements of the two vectors is usually
somewhere between 105 and 103 . That is, even though all the calculations have been done to approx-
imately 16 significant digits, the result is only accurate to three to ve significant digits! (To see how
much worse the result can be, repeat the above statements for n = 12.)
It is important to realize that most calculations in MATLAB are very accurate. It is not that solving
a matrix equation necessarily introduces lots of round-off errors; instead, Hilbert matrices are very un-
stable matrices working with them can lead to inaccurate results. On the other hand, most matrices
are quite stable. For example, if you repeat the above sequence of steps with a random matrix, you find
that the results are quite accurate. For example, enter
>> n = 1000; R = rand(n); x = rand(n, 1); b = R*x; xnum = R\b; max(abs(x - xnum))
The results are much more reassuring, even though n is 100 times as large for this random matrix as for
the Hilbert matrix and even though there are over 600,000 times as many floating point operations
needed to calculate x by Gaussian elimination for this random matrix!
Note: By entering all the statements on one line, it is easy to repeat this experiment many times for dif-
ferent random numbers by simply rerunning this one line.
81
5.3. Overdetermined and Underdetermined Linear Systems
is minimized. (The norm function is discussed in Sections 2.8 and 7.) This is called the least-squares
solution. This best approximation is calculated in MATLAB by typing
>> A\b
Analytically, the approximation can be calculated by solving
AT Ax = AT b .
However, numerically this is less accurate than the method used in MATLAB.
Note that this is the same operator used to find the solution to a square linear system. This cannot be
the intent here since A is not a square matrix. Instead, MATLAB interprets this operator as asking for
the least-squares solution. Again, this operator only makes sense if there is a unique solution which mini-
mizes the length of the vector Ax b. If there are an infinite number of least-squares solutions, MATLAB
warns you of this fact and then returns one of the solutions. For example, if
1 2 3 2
4 5 6 1
A= and b =
7 8 9 2
10 11 12 4
then Ax = b has no solutions, but has an infinite number of least-square approximations. If you enter
>> A\b
the response is
Warning: Rank deficient, rank = 2 tol = 1.4594e-14.
It also returns the solution (1/4 , 0, 29/60 )T (after using the MATLAB function rats which we discuss
below), which is one particular least-squares approximation. (If A is complex, solve AH Ax = AH b.)
Occasionally, if there are an infinite number of least-squares approximations, the solution desired is the
smallest one, i.e., the x for which the length of the vector x is minimized. This can be calculated us-
ing the pseudoinverse of A, also called the Moore-Penrose pseudoinverse, which is denoted by A+ . Since
A is not square, it cannot have an inverse. However, the pseudoinverse is the unique nm matrix which
satisfies the Moore-Penrose conditions:
AA+ A = A
A+ AA+ = A+
(AA+ )T = AA+
(A+ A)T = A+ A
In particular, if A is a square nonsingular matrix, then A+ is precisely A1 . This pseudoinverse is calcu-
lated in MATLAB by entering
>> pinv(A)
The reason for mentioning the pseudoinverse of A is that the least-squares approximation to Ax = b can
also be calculated by
>> pinv(A)*b
If there are an infinite number of least-squares approximations, this returns the one with the smallest
length. (In the previous example it is (13/45, 7/90, 4/9)T .)
Next, suppose that A Cmn with m < n. Ax = b is called an underdetermined system because there
are less equations than unknowns. In general, there are an infinite number of solutions to this equation.
We can find one particular solution by entering
>> A\b
This solution will have many of its elements being 0. We can also find the solution with the smallest
length by entering
>> pinv(A)*b
Warning: It is possible for an overdetermined system to have one or even an infinite number of solutions
(not least-squares approximations). It is also possible for an underdetermined system to have
no solutions.
One function which is occasionally useful is rats. If all the elements of A and b are rational num-
bers, then the solution and/or approximation obtained is usually a rational number, although stored as
82
6. File Input-Output
a floating-point number. This function displays a close rational approximation to the floating-point
number, which may or may not be the exact answer. For example, entering
>> rats(1/3 - 1/17 + 1/5)
results in the text variable 121/255, which is the correct answer.
Warning: Be careful when using this function. rats(sqrt(2)) makes no sense (as was known to
Pythagoras).
A\b When Ax = b is an overdetermined system, i.e., m > n where A Cmn , there are
usually no solutions, and this calculates the least-squares approximation; when it is an
underdetermined solution, i.e., m < n, there are usually an infinite number of solutions,
and this calculate the solution with the maximal number of zeroes.
pinv(A) The pseudoinverse of A.
6. File Input-Output
In Section 4.1 we discussed the csvread and csvwrite function which allow simple input from and
output to a file. The MATLAB functions fscanf and fprintf, which behave very similarly to their C
counterparts, allow much finer control over input and output. Before using them a file has to be opened
by
>> fid = fopen( 0 <file name> 0 , <permission string>)
where the file identifier fid is a unique nonnegative integer attached to the file. (Three file identifiers al-
ways exist as in C: 0 is the standard input, 1 is the standard output, and 2 is the standard error.) The
permission string specifies how the file is to be accessed:
0 0
r read only from the file.
0 0
w write only to the file (anything previously contained in the file is overwritten). If necessary, the
file is created.
0 0
a append to the end of the file (everything previously contained in the file is retained).
0
r+ 0 read from and write to the file (anything previously contained in the file is overwritten).
0
w+ 0 read from and write to the file (anything previously contained in the file is overwritten). If neces-
sary, the file is created.
If the fopen function fails, 1 is returned in the file identifier. Enter
>> fclose(fid)
if a file needs to be closed.
To write formatted data to a file, enter
>> fprintf(fid, <format string>, <variable 1>, <variable 2>, ...)
The elements contained in the variables are written to the file specified in a previous fopen function
according to the format string. These variables are printed out in order and matrices are converted to col-
umn vectors (i.e., A A(:) ). If fid is omitted, the output appears on the screen. The format string is
very similar to that of C, with the exception that the format string is cycled through until the end of the
file is reached or the number of elements specified by size is attained.
To briefly review some of the C format specifications, the conversion characters are:
d The argument is converted to decimal notation, and, if possible, to integer notation.
c The argument is a single character.
s The argument is a string.
e The argument is a floating-point number in E format.
f The argument is a floating-point number in decimal notation.
g The argument is a floating-point number in either E or decimal notation.
83
7. Some Useful Linear Algebra Functions
Each conversion character is preceded by %. The following may appear between the % and the con-
version character:
A minus sign which specifies left adjustment rather than right adjustment.
An integer which specifies a minimum field width.
If the maximum field width is larger than the minimum field width, the minimum field width is pre-
ceded by an integer which specifies the maximum field width, and the two integers are separated by a
period.
fprintf can also be used to format data on the screen by omitting the fid at the beginning of the
argument list. Thus, it is possible to display a variable using as little or as much control as desired. For
example, if x contains 23.6 three different ways to display it are
>> x
>> disp([ 0 x = 0 , num2str(x)])
>> fprintf( 0 %12.6e\n 0 , x)
and the results are
x =
-23.6000
x = -23.6000
-2.360000e+01
Note: It is easy to print the matrix A in the MATLAB workspace as we just described. However, it is
a little more difficult to print it to a file. The following works and can be entered on one line, al-
though it is actually a number of statements.
>> Str=num2str(A);for i = [1:size(Str, 1)] fprintf(fid, 0 %s\n 0 , Str(i,:));end
To read formatted data from a file, enter
>> A = fscanf(fid, <format string>, <size>)
The data is read from the file specified in a previous fopen function according to the format string and
put into the matrix A. The size argument, which puts an upper limit on the amount of data to be read, is
optional. If it is a scalar, or is not used at all, A is actually a vector. If it is [m n], then A is a matrix of
this size.
Advanced Input-Output
fopen( 0 <file name> 0 , Opens the file with the permission string determining how the
<permission string>) file is to be accessed. The function returns the file identifier,
which is a unique nonnegative integer attached to the file.
fclose(fid) Closes the file with the given file identifier.
fscanf(fid, <format string>) Behaves very similarly to the C command in reading data from
a file using any desired format.
fprintf(fid, <format string>, Behaves very similarly to the C command in writing data to a
<variable 1>,...) file using any desired format.
fprintf(<format string>, Behaves very similarly to the C command in displaying data on
<variable 1>,...) the screen using any desired format.
84
7. Some Useful Linear Algebra Functions
described in section 9.
chol
Let A Rnn be symmetric and positive definite . Then there exists an upper triangular matrix R
such that RT R = A. R is calculated by
>> R = chol(A)
If A is not positive definite, an error message is printed. (If A Cnn then RH R = A.)
cond
Note: Read the discussion on norm below first.
The condition number of A Cnn , which is denoted by cond(A), is a positive real number which is
always 1. It measures how stable A is: if cond(A) = the matrix is singular, while if cond(A) = 1
the matrix is as nice a matrix as you could hope for in particular, cond(I) = 1. To estimate the num-
ber of digits of accuracy you might lose in solving the linear system Ax = b, enter
log10(cond(A))
In Section 5.2 we discussed the number of digits of accuracy you might lose in solving Hx = b where H
is the Hilbert matrix of order 10. In doing many calculations it was clear that the solution was only accu-
rate to 3 to 5 significant digits. Since cond(H) is 1.61013 , it is clear that you should lose about 13 of
the 16 digits of accuracy in this calculation. Thus, everything fits.
If A is nonsingular, the condition number is defined by
It is calculated in MATLAB by
>> cond(A, p)
where p is 1, 2, Inf, or 0 fro 0 . If p = 2 the function can be shortened to
>> cond(A)
Note that the calculation of the condition number of A requires the calculation of the inverse of A. The
MATLAB function condest approximates the condition number without having to calculate this inverse.
See the discussion of this function below for further information on when it might be preferable.
Note: Sometimes we want to solve, or find the best approximation to, Ax = b when A Cmn is not a
square matrix. (This is discussed in detail in Section 5.3.) Since we still want to know the accuracy
of any solution, we want to generalize the condition number to nonsquare matrices. This is done by
defining the condition number of a nonsquare matrix in the 2-norm to be the ratio of the largest to
the smallest singular value of A, i.e., 1 /min{m,n} .
condest
Note: Read the discussion on cond above first.
The calculation of the condition number of A Cnn requires the calculation of its inverse. There are
two reasons this might be inadvisable.
The calculation of A1 requires approximately 2n3 flops, which might take too long if n is very
large.
If A is a sparse matrix (i.e., most of its elements are zero), we discuss in Section 9 how to store only
the nonzero elements of A to conserve storage. (For example, if n = 10,000 and A is tridiagonal ,
the number of nonzero elements in A is approximately 30,000 but the total number of elements in A
A Rnn is positive definite if xT Ax 0 for all x Rn and xT Ax = 0 only if x = 0. In practical terms, it
means that all the eigenvalues of A are positive. ( A Cnn is positive definite if xH Ax 0 for all x Cn and
xT Ax = 0 only if x = 0.)
A matrix is tridiagonal if its only nonzero elements occur on the main diagonal or on the first diagonal above
or below the main diagonal
85
7. Some Useful Linear Algebra Functions
is 100,000,000.) Since the inverse of a sparse matrix is generally much less sparse (in fact it may have
no zero elements at all), MATLAB may not be able to store A1 .
The function condest calculates a lower bound to the condition number of a matrix in the 1-norm with-
out having to determine its inverse. This approximation is almost always within a factor of ten of the
exact value.
When MATLAB calculates A\b or inv(A), it also calculates condest(A). It checks if its estimate
of the condition number is large enough that A is likely to be singular. If so, it returns an error message
such as
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 2.055969e-18.
where RCOND is the inverse of condest(A).
det
Let A Cnn . The determinant of A is calculated by
>> det(A)
det(A) = 0 if and only if A is singular. However, due to round-off errors it is very unlikely that you will
obtain 0 numerically unless all the entries to A are integers. For example, consider the matrix
0.95 0.03
C= .
0.05 0.97
eig
Let A Cnn . A scalar C is an eigenvalue of A if there exists a nonzero vector v Cn such that
Av = v ;
v is called the eigenvector corresponding to . There are always n eigenvalues of A, although they need
not all be distinct. MATLAB will very happily calculate all the eigenvalues of A by
>> eig(A)
It will also calculate all the eigenvectors by
>> [V, D] = eig(A)
D Cnn is a diagonal matrix containing the n eigenvalues on its diagonal and the corresponding eigen-
vectors are found in the same columns of the matrix V Cnn .
Note: This is the first time we have had a function return more than one argument. We discuss this nota-
tion in detail in Section 8.3. For now, we simply state that when [V, D] occurs on the right side
of the equal sign it means the matrix whose first columns come from V and whose last columns
come from D. However, on the left side of the equal sign it means that the function returns two
arguments where the first is stored in the variable V and the second in D.
eig can also calculate all the eigenvalues of the generalized eigenvalue problem
Ax = Bx
by
>> eig(A, B)
A matrix is defective if it has less eigenvectors than eigenvalues. MATLAB normally cannot determine
when this occurs. For example, the matrix
1 1
B=
0 1
86
7. Some Useful Linear Algebra Functions
is defective since it has two eigenvalues, both of which are 1, but it only has one eigenvector, namely
(1, 0)T . If you enter
>> B = [1 1; 0 1]; [V, D] = eig(B)
MATLAB calculates the two eigenvalues correctly, but it finds the two eigenvectors (1, 0)T and
T
(1, 2.21016 ) . Clearly the latter eigenvector should be (1, 0)T so that, in fact, there is only one
eigenvector.
Note: If A is a sparse matrix, you cannot use eig. You either have to use the function eigs or do
eig(full(A)).
eigs
Note: Read the discussion on eig above first.
Frequently, you do not need all the eigenvalues of a matrix. For example, you might only need the
largest ten in magnitude, or the five with the largest real part, or the one which is smallest in magnitude,
or . . . . Or you might only need a few of the generalized eigenvalues of Ax = Bx. eigs can do all of this.
Of course, this means that there are numerous possible arguments to this function so read the documenta-
tion carefully.
Why not just use eig anyway? Calculating all the eigenvalues of a nonsymmetric A Rnn requires
(very) approximately 10n3 flops, which can take a very long time if n is very large. On the other hand,
calculating only a few eigenvalues requires many, many fewer flops. If A is a full matrix, it requires cn2
flops where c is of reasonable size; if A is a sparse matrix, it requires cn flops.
Note: If A is sparse, you cannot use eig you will first have to do eig(full(A)).
Also, this function generates lots of diagnostic output. To calculate the largest 3 eigenvalues of A in
magnitude without generating any diagnostics, enter
>> op.disp = 0
>> eigs(A, 3, 0 LM 0 , op)
( op.disp is a structure, which was discussed in Section 3.4.)
inv
To calculate the inverse of the square matrix A Cnn enter
>> inv(A)
The inverse of A, denoted by A1 , is a matrix such that AA1 = A1 A = I, where I Rnn is the iden-
tity matrix. If such a matrix exists, it must be unique.
MATLAB cannot always tell whether this matrix does, in fact, exist. For example, the matrix
1 2
A=
2 4
does not have an inverse. If you try to take the inverse of this matrix, MATLAB will complain that
Warning: Matrix is singular to working precision.
It will display the inverse matrix, but all the entries will be Inf.
The above matrix was very simple. The matrix
1 2 3
A = 4 5 6 (7.1)
7 8 9
also does not have an inverse. If you ask MATLAB to calculate the inverse of A, it will complain that
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 2.055969e-18.
( RCOND is the inverse of a numerical approximation to the condition number of A; see condest above.)
That is, MATLAB is not positive that A is singular, because of round-off errors, but it thinks it is likely.
However, MATLAB still does try to calculate the inverse. Of course, if you multiply this matrix by A
the result is nowhere close to I. (Try it!) In other words, be careful and read (and understand) all
87
7. Some Useful Linear Algebra Functions
warning messages.
lu
Let A Cnn . Then there exists an upper triangular matrix U, a unit lower triangular matrix L , and
a permutation matrix P such that
LU = PA .
The MATLAB function lu calculates these matrices by entering
>> [L, U, P] = lu(A)
If A is invertible, all the elements of U on the main diagonal are nonzero. If you enter
>> A = [1 2 3; 4 5 6; 7 8 9]; [L, U, P] = lu(A)
where A is the singular matrix defined earlier, u33 should be zero. Entering
>> U(3,3)
displays 1.1102e-16, which clearly should be zero as we discussed in Section 1.5.
norm
The norm of a vector or matrix is a nonnegative real number which gives some measure of the size of
the vector or matrix. (It was briefly discussed in Section 2.8.) The pth norm of a vector is defined by
n 1/p
X
|xi |p if p [1, )
kxkp = i=1
max |xi | if p = .
1in
null
Let A Cnn . We can calculate an orthonormal basis for the null space of A by
>> null(A)
orth
Let A Cnn . We can calculate an orthonormal basis for the columns of A by
>> orth(A)
A unit lower triangular matrix is lower triangular and, in addition, all the elements on the main diagonal
are 1.
P is a permutation matrix if its columns are a rearrangement of the columns of I.
88
7. Some Useful Linear Algebra Functions
qr
Let A Rmn . Then there exists an orthogonal matrix Q Rmm and an upper triangular matrix
R Rmn such that
A = QR .
(If A Cmn then there exists an unitary matrix Q Cmm and an upper triangular matrix R Cmn
such that A = QR.) We calculate Q and R in MATLAB by entering
>> [Q, R] = qr(A)
It is frequently preferable to add the requirement that the diagonal elements of R be decreasing in magni-
tude, i.e., |ri+1,i+1 | |ri,k | for all i. In this case
AE = QR
A = QR .
It is calculated by
>> [Q, R] = qr(A, 0)
This is equivalent to applying the Gram-Schmidt algorithm to A.
pinv
The Moore-Penrose pseudoinverse has already been discussed in Section 5.3. We include it here for
completeness. It is calculated by using the singular value decomposition, which we discuss below.
rank
Let A Cmn . The rank of A is the number of linearly independent columns of A and is calculated by
>> rank(A)
This number is calculated by using the singular value decomposition, which we discuss below.
svd
Let A Rmn . A can be decomposed into
A = UVT
where U Rmm and V Rnn are orthogonal matrices and Rmn is a diagonal matrix (although
not necessarily square) with real nonnegative elements in decreasing order. That is,
1 2 min{m,n} 0 .
(If A Cmn then U Cmm and V Cnn are unitary matrices and Rmn is again a diagonal
matrix with real nonnegative elements in decreasing order.) These matrices are calculated by
>> [U, S, V] = svd(A)
Q Rmm is orthogonal if Q1 = QT . ( Q Cmm is unitary if Q1 = QH .)
89
7. Some Useful Linear Algebra Functions
The diagonal elements of are called the singular values of A. Although A need not be a square ma-
trix, both AT A Rnn and AAT Rmm are square symmetric matrices. (If A is complex, AH A and
AAH are both square Hermitian matrices.) Thus, their eigenvalues are nonnegative. Their nonzero eigen-
values are the squares of the singular values of A. In addition, the eigenvectors of AT A are the columns of
V and those of AAT are the columns of U. (If A is complex, the eigenvectors of AH A are the columns of
V and those of AAH are the columns of U.)
The best numerical method to determine the rank of A is to use its singular values. For example, to see
that
1 2 3 4
A = 5 6 7 8
9 10 11 12
has rank 2, use the svd function to find that the singular values of A are 25.4368, 1.7226,
and 8.10791016 . Clearly the third singular value should be 0 and so A has 2 nonzero singular values
and so has a rank of 2. On the other hand, the Hilbert matrix of order 15 has singular values
according to MATLAB. Following Principle 1.2, you can see there is no separation between the singular
values which are clearly not zero and the ones which are close to eps. Thus, you cannot conclude that
any of these singular values should be set to 0. Our best guess is that the rank of this matrix is 15.
The eigenvalues of a real square symmetric matrix are nonnegative. (The eigenvalues of a complex square
Hermitian matrix are real and nonnegative.)
For example, if m > n there are n singular values and their squares are the eigenvalues of AT A. The m
eigenvalues of AAT consist of the squares of these n singular values and mn additional zero eigenvalues.
In fact, it can be proven that the Hilbert matrix of order n is nonsingular for all n, and so its rank is
truly n. However, if you enter
>> rank( hilb(15) )
you obtain 12, so that MATLAB is off by three.
90
8.1. Control Flow and Logical Variables
8. Programming in MATLAB
Using the functions we have already discussed, MATLAB can do very complicated matrix operations.
However, sometimes there is a need for finer control over the elements of matrices and the ability to test,
and branch on, logical conditions. Although prior familiarity with a high-level programming language is
useful, MATLABs programming language is so simple that it can be learned quite easily and quickly.
<expression> can be a matrix in which case each column vector is stored one at a time in i.
91
8.1. Control Flow and Logical Variables
if <logical expression>
<statement>
...
<statement>
end
where the statements are evaluated as long as the <logical expression> is true. The
<logical expression> is generally of the form
<arithmetic expression-left> rop <arithmetic expression-right>
where rop is one of the r elational operators shown below. Some examples of logical expressions are
i == 5
x(i) >= i
imag(A(i,i)) = 0
sin(1) - 1 < x(1) + x(i) 3
Is i equal to 5? Is xi i? Is the imaginary part of ai,i nonzero? Is sin 1 1 < x1 + x3i ?
We can compare complex numbers to determine whether or not they are equal. However, mathemati-
cally we cannot apply the other four relational operators. For example, what does 2 + 3i < 3 + 2i mean?
However, in MATLAB only the real parts of complex numbers are compared so
>> 2 + 3i < 3 + 2i
returns 1.
Warning: String variables cannot be compared by == or =. Instead, if a and b are text variables,
enter
>> strcmp(a, b)
The result is true if the two character strings are identical and false otherwise.
Relational Operators
92
8.1. Control Flow and Logical Variables
93
8.1. Control Flow and Logical Variables
Logical Operators
The second MATLAB loop structure is the while statement. The general form of the while loop is
while <logical expression>
<statement>
...
<statement>
end
where the statements are executed repeatedly as long as the <logical expression> is true. For exam-
ple, eps can be calculated by
ep = 1;
while 1 + ep > 1
ep = ep/2;
end
eps = 2*ep
It is possible to break out of a for loop or a while loop from inside the loop by using the break
statement as in C. This terminates the execution of the innermost for loop or while loop.
The continue statement is related to break. It causes the next iteration of the for or while loop
to begin immediately.
The switch function executes particular statements based on the value of a variable or an expression.
Its general form is
switch <variable or expression>
case <Value 1>
<statement group 1>
case {<Value 2a>, <Value 2b>, <Value 2c>, ..., <Value 2m>}
<statement group 2>
...
case <value n>
<statement group r>
otherwise
<statement group r+1>
end
where statement group 1 is evaluated if the variable or expression has <Value 1>, where statement group
2 is evaluated if the variable or expression has values <Value 2a> or <Value 2b> or <Value 2c>, etc.
(Note that if a case has more than one value, then all the values must be surrounded by curly brackets.)
The final otherwise is not required. If it occurs and if none of the values match the variable or expres-
sion, then statement group r+1 is evaluated. If it does not occur and if none of the values match, then
none of the statement groups are executed.
Warning: The switch function is different in MATLAB than in C in two ways:
First, in MATLAB the case statement can contain more than one value; in C it can only con-
tain one.
And, second, in MATLAB only the statements between the selected case and the following one
or the following otherwise or end (whichever occurs first) are executed; in C all the state-
ments following the selected case are executed up to the next break or the end of the block.
94
8.2. Matrix Relational Operators and Logical Operators
Control Flow
true Generates a logical matrix with all elements having the logical value true.
Use true or true(n) or true(m, n).
false Generates a logical matrix with all elements having the logical value false.
Use false or false(n) or false(m, n).
Although MATLAB does have a quite powerful programming language, it is needed much less fre-
quently than in typical high-level languages. Many of the operations and functions that can only be
applied to scalar quantities in other languages can be applied to vector and matrices in MATLAB. For
example, MATLABs relational and logical operators can also be applied to vectors and matrices. In this
way, algorithms that would normally require control flow for coding in most programming languages can
be coded using simple MATLAB functions.
If A, B Rmn then the relational equation
>> C = A rop B
is evaluated as cij = aij rop bij , where rop is one of the relational operators defined previously. C is a
logical array, that is, its data type is logical not numeric. The elements of C are all 0 or 1: 0 if
aij rop bij is a false statement and 1 if it is a true one. Also, the relational equation
>> C = A rop c
is defined when c is a scalar. It is evaluated as if we had entered
>> C = A rop c*ones(size(A))
Similar behavior holds for logical operators:
>> C = A & B
means cij = aij & bij ,
>> C = A | B
means cij = aij | bij ,
>> C = A
means cij = aij , and
>> C = xor(A, B)
means cij = xor(aij , bij ). Again the elements of C are all 0 or 1.
To show the power of these MATLAB functions, suppose we have entered
>> F = rand(m, n)
95
8.2. Matrix Relational Operators and Logical Operators
and now we want to know how many elements of F are greater than 0.5. We can code this as
nr elements = 0;
for i = 1:m
for j = 1:n
if F(i,j) > 0.5
nr elements = nr elements + 1;
end
end
end
nr elements
However, it can be coded much more simply, quickly, and efficiently since the relational expression
>> C = F > 0.5;
or, to make the meaning clearer,
>> C = (F > 0.5);
generates the matrix C where
1 if fij > 0.5
n
cij =
0 otherwise.
Since the number of ones is the result we want, simply enter
>> sum( sum( F > 0.5 ) )
or
>> sum(sum(C))
or
>> sum(C(:))
And suppose we want to replace all the elements of F which are 0.5 by zero. This is easily done by
>> F = F.*(F > 0.5)
The relational expression F > 0.5 generates a matrix with zeroes in all the locations where we want to
zero the elements of F and ones otherwise. Multiplying this new matrix elementwise with F zeroes out all
the desired elements of F. We can also replace all the elements of F which are 0.5 by using
>> C = (F > 0.5)
>> F = F.*C - pi*( C)
Shortly we will present two easier ways to do this.
There is even a MATLAB function which determines the locations of the elements of a vector or a ma-
trix where some property is satisfied. The function
>> find(x)
generates a column vector containing the indices of x which are nonzero. (Recall that nonzero can also
mean TRUE so that this function finds the elements where some condition is true.) For example, if
x = (0, 4, 0, 1, 1, 0, )T then the resulting vector is (2, 4, 5, 7)T . We can add 10 to every nonzero ele-
ment of x by
>> ix = find(x);
>> x(ix) = x(ix) + 10;
Note: If no element of the vector x is nonzero, the result is the empty matrix [] and the following state-
ment is not executed.
Note: There is a similar function which finds if a substring is contained in a string.
>> k = strfind(str, pattern)
returns the starting index for any and all occurrence ofs pattern in str.
find can also be applied to a matrix. The function
>> find(A)
first transforms A to a column vector (i.e., A(:) ) and then determines the locations of the nonzero ele-
ments. As a simple example of the power of this function we can add 10 to every nonzero element of A
by
>> ijA = find(A);
>> A(ijA) = A(ijA) + 10
Or we can work with the matrix directly by entering
>> [iA, jA] = find(A)
The two column vectors iA and jA contain the rows and columns, respectively, of the nonzero elements.
We can also find the locations of the nonzero elements and their values by
96
8.2. Matrix Relational Operators and Logical Operators
97
8.2. Matrix Relational Operators and Logical Operators
We can also convert a non-logical variable to a logical one by using the MATLAB function logical.
To explain logical arrays more clearly, we take a specific and very simple example. Enter
>> v = [0:.25:1];
>> c = (v >= .5);
so that v = [0 .25 .5 .75 1.0] and c = [0 0 1 1 1] where 0 denotes false and 1 denotes true.
The result of
>> v(c)
is [.5 .75 1.0]. That is, c is a logical vector and v(c) deletes the elements of v which are false.
On the other hand
>> iv = find(v < .5);
returns iv = [1 2] and
>> v(iv) = [];
returns v = [.5 .75 1.0]. The difference between c and iv is that c is a logical vector and iv is a
scalar vector. If you enter
>> v([0 0 1 1 1]) % WRONG
instead of
>> v(c)
you obtain the error message
??? Subscript indices must either be real positive integers or logicals.
because [0 0 1 1 1] is a numeric vector and so must contain the numbers of the elements of v which
are desired but there is no element 0.
MATLAB also has two functions that test vectors and matrices for logical conditions. The function
>> any(x)
returns 1 if any element of the vector x is nonzero (i.e., TRUE); otherwise 0 is returned. When
applied to a matrix, it operates on each column and returns a row vector. For example, we can check
whether or not a matrix is tridiagonal by
>> any( any( triu(A, 2) + tril(A, -2) ) )
Here we check all the elements of A except those on the main diagonal and on the two adjacent ones. A
result of 1 means that at least one other element is nonzero. If we want a result of 1 to mean that A is
tridiagonal we can use
>> any( any( triu(A, 2) + tril(A, -2) ) )
instead. The function
>> any(A)
operates columnwise and returns a row vector containing the result of any as applied to each column.
The complementary function all behaves the same as any except it returns 1 if all the entries are
nonzero (i.e., TRUE). For example, you can determine if a matrix is symmetric by
>> all( all(A == A. 0 ) )
A result of 1 means that A is identical to AT .
It is also easy to check if two arrays (including structures and cells) have exactly the same contents.
The function
>> isequal(A, B)
returns true if all the contents are the same and false otherwise. This means that (nonempty) arrays
must have the same data type and be the same size.
For completeness we mention that MATLAB has a number of other functions which can check the
status of variables, the status of the elements of vectors and matrices, and even of their existence. For ex-
ample, you might want to zero out all the elements of a matrix A which are Inf or NaN. This is easily
done by
>> A( find( isfinite(A) ) == false ) = 0
or
>> A( find( isfinite(A) ) == true ) = 0
where isfinite(A) generates a matrix with 1 in each element for which the corresponding element of A
is finite. To determine if the matrix A even exists, enter
exist( 0 A 0 )
See the table below for more details and more functions.
98
8.3. Function M-files
Logical Functions
all True if all the elements of a vector are true; operates on the columns of a
matrix.
any True if any of the elements of a vector are true; operates on the columns of a
matrix.
exist( 0 <name> 0 ) False if this name is not the name of a variable or a file. If it is, this function
returns:
1 if this is the name of a variable,
2 if this is the name of an m-file,
5 if this is the name of a built-in MATLAB function.
find The indices of a vector or matrix which are nonzero.
ind2sub Converts indices of a matrix A from A(:), the column vector form, to A, the
matrix form.
sub2ind Converts indices of a matrix A from A, the matrix for, to A(:), the column
vector form.
logical Converts a numeric variable to a logical one.
strfind Find any and all occurrences of a substring in a string.
[2pt] iscell True for a cell array.
ischar True for a character array.
iscolumn True for a column vector.
isempty True if the array is empty, i.e., [].
isequal Tests if two (or more) arrays have the same contents.
isfield True if the argument is a structure field.
isfinite Generates an array with 1 in all the elements which are finite (i.e., not Inf or
NaN ) and 0 otherwise.
isfloat True if a floating-point array.
isinf Generates an array with 1 in all the elements which are Inf and 0 otherwise.
islogical True for a logical array.
ismember Generates an array with 1 in all the elements which are contained in another
array.
isnan Generates a matrix with 1 in all the elements which are NaN and 0 otherwise.
isnumeric True for a floating-point array.
isprime Generates an array with 1 in all the elements which are prime numbers. Only
non-negative integers are allowed in the elements.
isreal True for a real array, as opposed to a complex one).
isrow True for a row vector.
isscalar True for a scalar variable.
issparse True for a sparse array.
isstruct True for a structure array.
isvector True for a vector, as opposed to a matrix.
We have already discussed script m-files, which are simply an easy way to collect a number of state-
ments and execute them all at once. Function m-files, on the other hand, are similar to functions or pro-
cedures or subroutines or subprograms in other programming languages. Ordinarily, variables which are
created in a function file exist only inside the file and disappear when the execution of the file is completed
these are called local variables. Thus you do not need to understand the internal workings of a function
file; you only need to understand what the input and output arguments represent.
Note: The generic term for script files and function files is m-files, because the extension is m.
Unlike script files, function files must be constructed in a specific way. The first line of the file
<file name>.m must begin with the keyword function. Without this word, the file is a script file. The
complete first line, called the function definition line, is
99
8.3. Function M-files
If you are worried because passing arguments by value might drastically increase the execution time of the
function, we want to reassure you that this does not happen. To be precise, MATLAB does not actually pass all
the input arguments by value. Instead, an input variable is only passed by value if it is modified by the func-
tion. If an input variable is not modified, it is passed by reference. (That is, the input argument is the actual
variable used in the calling statement and not a local copy.) In this way you get the benefit of call by value
without any unnecessary overhead. And how does MATLAB know if an input argument is modified? It can only
be modified if it appears on the left-hand side of an equal sign inside the function!
100
8.3. Function M-files
101
8.3. Function M-files
We can spruce this function up to have default values for and a and also to calculate its derivative
with the following function file.
function [out1, out2] = spruce(x, xi, a)
% spruce: a silly function to make a point, f(x,xi,a) = sin(x)*exp(-a*(x-xi) 2)
% if only x is input, xi = 0 and a = 1
% if only x and xi are input, a = 1
% if only one output argument, f(x,xi,a) is calculated
% if two output arguments, f(x,xi,a) and f(x,xi,a) are calculated
if nargin == 1
xi = 0;
a = 1;
elseif nargin == 2
a = 1;
end
out1 = exp(-a.*(x-xi). 2).*sin(x);
if nargout == 2
out2 = exp(-a.*(x-xi). 2).*(cos(x) - 2.*a.*(x-xi).*sin(x));
end
If there is only one input argument then is set to 0 and a is set to 1 (which are useful default val-
ues) while if there are only two input arguments then a is set to 1. If there is only one output argument
then only f (x) is calculated, while if there are two output arguments then both f (x) and f 0 (x) are
102
8.3. Function M-files
calculated.
Also, note that x can be a scalar (i.e., a single value) or it can be a vector. Similarly, and a can
each be a scalar or a vector. If x is a vector, i.e., (x1 , x2 , . . . , xn )T , while and a are scalars, then the
function is 2
f (xi , , a) = ea(xi ) sin(xi ) for i = 1, 2, . . . , n ,
and all the values can be calculated in one call to spruce. If, on the other hand, x, , and a are all vec-
tors, then the function is
2
f (xi , i , ai ) = eai (xi i ) sin(xi ) for i = 1, 2, . . . , n ,
and, again, all the values can be calculated in one call to spruce.
A common error which writing a function m-file is forgetting that the argument(s) might be vectors or
matrices. For example, we mentioned the Heaviside step function in Some Common Real Mathematical
Functions on page 13, but pointed out that it is in a toolbox which you might not have. We could write it
as
function Y = myheaviside scalar(x)
if x < 0
y = 0;
elseif x == 0
y = 0.5;
else
y = 1;
end
but this will only work if x is a scalar. For example,
>> myheaviside scalar([-3:3])
returns
ans =
1
Note that the function does not return an error message it simply returns an incorrect result. (Inci-
dentally, myheaviside scalar([-6:0]) also returns 1.) The following function, however, will work in all
cases.
function Y = myheaviside(X)
Y = zeros(size(X));
Y(X>0) = 1;
Y(X==0) = 0.5;
(The input and output arguments are capitalized to indicate that they can be matrices.) For example,
>> myheaviside([-3:3])
returns
ans =
0 0 0 0.5000 1.0000 1.0000 1.0000
We have now presented all the essential features of the MATLAB programming language, and it cer-
tainly is a minimal language. MATLAB can get away with this because most matrix operations can
be performed directly unlike in most other programming languages. You only need to write your own
function if MATLAB cannot already do what you want. If you want to become proficient in this language,
simply use the type command to look at the coding of some functions.
Now that we have discussed the essentials of programming in MATLAB, it is necessary to discuss how
to program correctly. When you are entering one statement at a time in the text window, you immediately
see the result of your calculation and you can determine whether or not it is correct. However, in an m-file
you have a sequence of statements which normally end with semicolons so that you do not see the inter-
mediate calculations. What do you do if the result is incorrect? In other words, how do you debug your
m-file?
There are a number of simple techniques you can use and we discuss them in turn. In a script m-file
intermediate calculations are normally not printed out, but they are still available to look at. This can fre-
quently lead to an understanding of where the calculation first went wrong. However, this is not true of
function m-files since all the local variables in the function disappear when the function ends. Of course,
with any m-file you can selectively remove semicolons so that intermediate results are printed out. This is
probably the most common method of debugging programs no matter what programming language is
103
8.3. Function M-files
being used.
When loops are involved (either using for or while statements), the printed output can seem to be
endless (and it is endless if you are in an infinite loop). And it is usually impossible to read the output
since it is zipping by at (what appears to be) nearly the speed of light! The pause function can slow
down or even stop this output. By itself pause stops the m-file until some key is pressed while
pause(<floating-point number>)
pauses execution for this many seconds or fractions of a second. (This is computer dependent, but
pause(0.01) should be supported on most platforms.) You can even turn these pauses on and off by
using pause on and pause off.
Note: Occasionally, you will forget that you have put the function
pause
into your code and wonder why it is taking so long to execute. The alternative
input( 0 Press Enter to continue 0 , 0 s 0 );
pauses the code and also reminds you that it has been paused.
The echo command is also useful for debugging script and function m-files, especially when if state-
ments are involved. Typing
>> echo on
turns on the echoing of statements in all script files (but not printing the results if the statements end
with semicolons), and echo off turns echoing off again. However, this does not affect function files. To
turn echoing on for a particular function, type
>> echo <function name> on
and to turn echoing on for all functions, type
>> echo on all
The keyboard command is also very useful for debugging m-files. It stops execution of the m-file, simi-
lar to the pause function. However, it returns complete control to the user to enter any and all MATLAB
statements. In particular, you can examine any variables in the functions workspace. If desired, you can
also change the value of any of these variables. The only way you will recognize this is not a standard
MATLAB session is that the prompt is
K>>
for Keyboard. To terminate the keyboard session and return control to the m-file, enter
K>> return
To terminate both the keyboard session and the execution of the m-file, enter
K>> dbquit
When using the debugger, you are not running your program. Instead, you are running the debugger
and it is running your program. Thus, many of the commands you enter are commands for the debug-
ger; to distinguish these commands from normal MATLAB commands/functions they begin with db.
There are two ways to run the debugger: you can type the debugger commands into the workspace, or in
a MATLAB window you can use the mouse and click on the corresponding icons.
In addition, you are still in the workspace so many MATLAB statements can still be executed. For ex-
ample, to see the values of variables just type the variable name into the workspace. (Alternatively, you
can move the mouse over the variable name in the window and its description and value(s) will be shown.)
Also, you can run most MATLAB statements as long as you do not try to create new variables (but you
can modify existing variables).
We will not discuss the commands in this debugger in detail, but only provide a brief description of
each one, because these are similar to commands in any debugger. If you have experience with using a
debugger, doc will give you complete details.
104
8.3. Function M-files
Debugging Commands
Some, but not all, of these commands can be found in the MATLAB editor window when you are edit-
ing a MATLAB script or function. It is necessary to set one or more breakpoints to stop the execution of
the code so that you can take control. This is easily done by using the left mouse button to click on the
dashes just to the right of the line numbers, which will cause a small red circle to appear to remind you of
the breakpoints.
Now we want to discuss the arguments in a MATLAB function, since they are are used somewhat differ-
ently than in other programming languages. For example, in
function out = funct1(a, t)
a and t are the input arguments and out is the output argument. Any and all input variables are lo-
cal to the function and so can be modified without affecting the arguments when the function funct1 is
called. (This is true no matter what type of variables they are.) In
function [out1, out2, out3] = funct2(z)
z is the only input argument and there are three output arguments, each of which can be any type of
variable. There is no requirement that all three of these output arguments actually be used. For example,
the calling statement might be any of the following:
>> art = funct2(1.5)
>> [physics, chemistry] = funct2([1 2 3])
>> [math, philosophy, horticulture] = funct2(reshape([1:30], 6, 5))
(just to be somewhat silly).
As an aside, it is even possible to not output some of the former arguments. Some examples are
>> [ , chemistry] = funct2([1 2 3])
>> [ , philosophy, horticulture] = funct2(reshape([1:30], 6, 5))
>> [ , , horticulture] = funct2(reshape([1:30], 6, 5))
where is a placeholder for an output argument. It is never necessary to use it in this way, but it
makes a code easier to read. When an output argument is given a name, anyone reading the code will
expect it to be used later in the code and so, if it isnt, why isnt it? I used to use the variable name
dummy for an unneeded output argument, but this is far preferable.
In MATLAB input arguments occur on the right side of the equal sign and output arguments occur on
the left. Arguments which are to be modified by the function must occur on both sides of the equal sign
in the calling statement. For example, in funct2 if z is modified and returned in out1 then the calling
sequence should be
>> [z, b, c] = funct2(z)
where z appears on both sides of the equal sign. (There is an alternative to this awkward use of param-
eters which are modified by the function: you can make a variable global, as we discuss at the end of this
section. However, this is not usually a good idea.)
There is another difference between MATLAB and most other programming languages where the type
105
8.3. Function M-files
of each variables has to be declared, either explicitly or implicitly. For example, a variable might be an
integer, a single-precision floating-point number, a double-precision floating-point number, a character
string, etc. In MATLAB, on the other hand, there is no such requirement. For example, the following
statements can follow one another in order and define x to be a string variable, then a vector, then a
scalar, and finally a matrix.
>> x = 0 WOW? 0
>> x = x + 0
>> x = sum(x)
>> x = x*[1 2; 3 4]
It is particularly important to understand this typelessness when considering output arguments. For ex-
ample, there are three output arguments to funct2 and any of them can contain any type of variable. In
fact, you can let the type of these arguments depend on the value or type of the input argument. This is
probably not something you should want to do frequently, but it is sometimes very useful.
Occasionally, there is a need to pass values from the workspace to a function or to pass values between
different functions without using the input arguments. (As we discussed earlier, this may be desirable if a
variable is modified by a function.) In C this is done by using global variables. MATLAB also has global
variables which are defined by declaring the variables to be global using
>> global <variable 1> <variable 2> <variable 3> ...
By the way, a variable is a global variable if it appears in a global statement and a local variable if it does
not. (Note that a variable can be a local variable in one function and a global variable in another.) This
statement must appear in every function which is to share the variables. If the workspace is also to share
these variables, you must type this statement (or be put into a script file which you execute) before these
variables are used.
Warning: Spaces, not commas, must separate the variables in a global statement
Warning: Using global statements is generally considered to be very bad practice.
Instead of using a global variable, it is frequently preferable to save the value of a local variable between
calls to the function. Normally, local variables come into existence when the function is called and dis-
appear when the function ends. Sometimes it is very convenient to be able to save the value of a local
variable so that it will still be in existence when the function is next called. In C, this is done by declaring
the variable static. In MATLAB it is done by declaring the variable persistent using
>> persistent <variable 1> <variable 2> <variable 3> ...
Warning: Spaces, not commas, must separate the variables.
Note: The first time you enter the function, a persistent variable will be empty, i.e., [], and you can test
for this by using isempty.
We now present a simple example where persistent variables are very helpful. Suppose we want to write
a function m-file to evaluate
y2
h(y) =
y1 (1 y12 ) y2 + cos t
where , , , and are parameters which will be set initially and then left unchanged during a run.
(The parameter Gamma is capitalized even though it is not a matrix because is very different from .)
We might be studying a mathematical model where this function will be evaluated many, many times
for different values of y. For each experiment these parameters will be fixed, but they will be different
for each experiment. We do not want to hardcode the values in the function because we would have to
repeatedly change the function which is very undesirable. Certainly we can write the function as
function z = fncz1(y, alpha, beta, Gamma, omega)
z = [ y(2) ; -y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ];
but then we have to include these four parameters in each call to the function. We can always simplify
this function by combining the four parameters into one structure by
function z = fncz2(y, param)
z = [ y(2) ; -y(1)*(1-param.beta*y(1) 2)-param.alpha*y(2)+...
param.Gamma*cos(param.omega*t) ];
but then it is harder to read the equation. (If this function was more complicated it would be much
harder to read.) To make this last function easier to read we could write it as
106
8.3. Function M-files
A closure is a complicated term to explain. In this context it means that the parameters used when the func-
tion is defined are saved and can be referenced when the function is later used.
107
8.3. Function M-files
code up into a number of functions, each of which can be easily understood and debugged. In MATLAB
functions normally have to be separated into different files so that each function and its file name agree;
otherwise, MATLAB cannot find the function. This can be annoying if a number of files have to be cre-
ated: for example, it can be difficult to remember the purpose of all these functions, and it can be difficult
to debug the primary function. MATLAB has a feature to handle this proliferation of files; function m-
files can contain more than one function. The first function in the file is called the primary function and
its name must agree with the name of the file. There are two further types of functions: Any remaining
functions are called subfunctions or nested functions. (At the end of Section 10.2 we code the function
gravity using a number of nested functions.)
Note: The primary function or a subfunction begins with the function definition line (i.e., the line which
begins with the keyword function ). It is possible to end the primary function and each subfunc-
tion with the statement end, but this is not necessary because MATLAB recognizes that a function
has ended when it encounters the next function statement. However, if a nested function is used
then it and all other functions must end with the end statement.
First, we discuss subfunctions, which are quite simple. They are placed following the primary function
and between or following other subfunctions. For example,
function primary function
% code for the primary function
function subfunction1
% code for the first subfunction
function subfunction2
% code for the second subfunction
They are only visible to the primary function and to other subfunctions in the same file. Thus, different
m-files can contain subfunctions with the same name. Also, the help, lookfor, and type commands
can only access the primary file. It is crucial to understand that variables in the primary function or in a
subfunction are local to that function and unknown outside it (unless they are declared to be global ).
The only way to pass variables between these functions is through the argument list.
Usually, subfunctions are sufficient and they are much easier to describe. When they are not suffi-
cient, we have nested functions. Its main advantage (as far as we are concerned) is that variables can be
passed into and out of a nested function without being in the argument list. Nested functions are more
complicated than subfunctions and we will only provide a brief discussion.
To make this discussion specific, consider the following function m-file.
They are similar to internal functions in Fortran 95, and they are somewhat related to inner classes in Java
but not in C++.
108
8.3. Function M-files
A nested function is within another function. For example, the nested functions nest 1 and nest 2 are
nested within the primary function nested ex, and the nested function nest 3 is nested within the sub-
function sub 1. (Nested functions can have other nested functions within them, but enough is enough.)
The important concept to understand when using nested functions is the scope of variables in the func-
tion m-file. The scope of a variable is the context within which it is defined, i.e., where it can be set, mod-
ified, and used. Now let us consider a function workspace. The workspace of the primary function is also
independent of the workspace of each subfunction. However, since a nested function is within one or more
other functions, it is within the workspace of this function or these functions. In the function nested ex
the nested functions nest 1 (lines 715) and nest 2 (lines 1623) have access to the variables p1, p2,
and p3 of the primary function (lines 126). They also have access to the subfunction sub 1 (lines 27
37) (but not any of its variables) as shown in line 13. Note that nest 2 also has access to nest 1 as
shown in line 14.
To begin, a nested function can have local variables. Any variable in the argument list of a nested func-
tion is local to that function, and the same is true for any variable which contains values returned by the
109
8.3. Function M-files
function. Thus, the variable out1 is local to the function nest 1 and out2 is local to nest 2. Also,
the variable r is local to nest 1 and also local to nest 2. The variable r which is defined on line 4 is
unchanged by the calls to the two nested function. The value returned in line 24 will always be 5. Simi-
larly, the variables t and out3 are local to nest 3.
What about the remaining variables? The variables n1a and p are local to nest 1 (as shown in
line 18) and n2a is local to nest 2 because the outer function, i.e., nested ex does not define or use
them. Similarly, n3a is local to nest 3. Also, n1a cannot be accessed in nest 2 as shown in line 17.
(If n1a really needs to be passed to nest 2, then it must be in the workspace of nested ex. (This
could be done by adding n1a = 0 after line 3.) On the other hand, the variables p1 and p2 are defined
in nested ex and so can be used in nest 1 and nest 2. This is also true for p3 which is an output
variable in nested ex. Finally, note that n1b is not used in nested ex until line 25, after nest 1 and
nest 2 have been called, but it can still be used in nest 2 even though it was defined in nest 1.
CDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDB
FHEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEHG
FG FG
FG WARNING FG
FG FG
FG A common mistake when using nested functions is defining what you think is a FG
FG
FG local variable in a nested function and forgetting that the same variable name
FG
FG
FG is used in the outer function. It is hard to imagine making that mistake here FG
FG because the code is so short but it can easily happen in a real code. One so- FG
FG FG
FG lution is to append a special character to all local variables in nested functions FG
FG FG
FG (for example, append an underscore, i.e., , to the end of the name of each local FG
FG variable). FG
FG FG
FG FG
FHDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDHG
@EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEA
Just for completeness, none of the variables in nested ex can be accessed in sub 1 and vice versa.
For instance, p2 cannot be accessed in the subfunction sub 1 as we show on line 30.
Now let us return to the topic of how MATLAB finds a function. As we stated previously (but did not
discuss), when a function is called from within an m-file, MATLAB first checks if the function named is
the primary function or a subfunction in the current file. If it is not, MATLAB searches for the m-file in
the current directory. Then MATLAB searches for a private function by the same name (described below).
Only if all this fails does MATLAB use your search path to find the function. Because of the way that
MATLAB searches for functions, you can replace a MATLAB function by a subfunction in the current
m-file but make sure you have a good reason for doing so!
In the previous paragraph we described how to create a subfunction to replace one function by another
of the same name. There is another, more general, way to handle this replacement: you can create a sub-
directory in your current directory with the special name private. Any m-files in this subdirectory are
visible only to functions in the current directory. The functions in this subdirectory are called private
functions. For example, suppose we are working in the directory personal and have created a number of
files which use rref to solve linear systems. And suppose we have written our own version of this func-
tion, because we think we can calculate the reduced row echelon of a matrix more accurately. The usual
way to test our new function would be to give it a new name, say myrref, and to change the call to rref
in every file in this directory to myrref. This would be quite time-consuming, and we might well miss
some. Instead, we can code and debug our new function in the subdirectory private, letting the name of
our new function be rref and the name of the m-file be rref.m. All calls in the directory to rref will
use the new function we are testing in the subdirectory private, rather than MATLABs function. Even
more important, any function in any other directory which calls rref will use the MATLAB function and
not our new, improved version.
The final topic we will briefly discuss involves recursion. It is possible and sometimes useful for a
function to call itself. As a simple example, consider the Fibonacci sequence
110
8.4. Odds and Ends
A recursive code must be able to stop, and this code stops if n = 0 or n = 1. For larger values of n, the
function is called recursively.
Warning: This code is very, very, very inefficient. We have provided it simply to show how recursion can
lead to a very compact code. The reason this code is very inefficient is because it uses an in-
credibly large amount of CPU time for large n (and 50 is very, very, very large). In fact,
in order to calculate fn the function fibonacci is called recursively 2fn 2 times and fn
grows exponentially with n.
There are examples for which recursion is advantageous. However, our aim is simply to show how to use
it not whether to use it.
Function Commands
111
8.4. Odds and Ends
executes whatever statement or statements are contained in the string. For example, entering
>> s = 0 x = linspace(0, 10, n); y = x.*sin(x).*exp(x/5); plot(x, y) 0
>> eval(s)
executes all three statements contained in the string s. In addition, if an executed statement generates
output, this is the output of eval. For example, if we type
>> A = zeros(5,6);
>> [m, n] = eval( 0 size(A) 0 );
then m is 5 and n is 6.
There is a very practical applications for this function since it can combine a number of statements into
one. For example, suppose we want to work with the columns of the Hilbert matrix of size n and we want
to create variables to hold each column, rather than using H(:,i). We can do this by hand by typing
>> c1=H(:,1);
>> c2=H(:,2);
...
which gets tiring very quickly. Instead, we can do this by typing
>> for i = 1:n
eval( [ 0 c 0 num2str(i) 0 =H(:,i) 0 ] )
end
This requires some explanation. It might be a little clearer if we separate the statement inside the for
loop into two statements by
s = [ 0 c 0 , num2str(i), 0 =H(:,i) 0 ]
eval(s)
(where we include commas in the first statement for readability). s is a text variable which contains
c1=H(:,1) the first time the loop is executed, then c2=H(:,2) the second time, etc. (To understand
how s is created, recall that s is really just a row vector with each element containing the ASCII repre-
sentation of the corresponding character.)
Finally, there is a very esoteric application for this function that allows it to catch errors. This is similar
to the catch and throw commands in C++ and Java. To use this feature of eval, call it using two
arguments as
>> eval(<try string>, <catch string>)
The function executes the contents of <try string> and ignores the second argument if the execution
succeeds. However, if it fails then the contents of <catch string> are executed. (This might be a call
to a function which can handle the error.) If there is an error, the command lasterr returns a string
containing the error message generated by MATLAB.
A MATLAB function which is occasionally useful in a function is feval. It executes a function, usually
defined by an m-file, whose name is contained in a string by
>> feval(<string>, x1, x2, ..., xn)
(See below for other ways to pass the function in the argument list.) Here x1, x2, ..., xn are the
arguments to the function. For example, the following two statements are equivalent
>> A = zeros(5,6)
>> A = feval( 0 zeros 0 , 5, 6)
Suppose that in the body of one function, say sample, we want to execute another function whose
name we do not know. Instead, the name of the function is to be passed as an argument to sample.
Then feval can be used to execute this text variable. For example, suppose in function sample we want
to generate either linear or logarithmic plots. We can input the type of plot to use by
112
8.5. Advanced Topic: Vectorizing Code
There are two common ways to pass the function <type of plot> in the argument list:
(1) use a character string, e.g., feval( 0 loglog 0 , ...), or
(2) use a function handle, e.g., feval(@logval, ...), or
Note: eval and feval serve similar purposes since they both evaluate something. In fact, feval can
always be replaced by eval since, for example, feval( 0 zeros 0 , 5, 6) can always be replaced by
eval( 0 zeros(5,6) 0 ). However, there is a fundamental difference between them: eval requires
the MATLAB interpreter to completely evaluate the string, whereas feval only requires MATLAB
to evaluate an already existing function. feval is much more efficient, especially if the string must
be evaluated many times inside a loop.
As long as your MATLAB code executes quickly, there is no need to try to make it faster. However, if
your code is executing slowly, you might be willing to spend some time trying to speed it up. There are
three standard methods to speed up a code:
(0) Preallocate matrices as shown in the function prealloc on page 101. This is very simple and very
effective if the matrices are large.
(1) Use MATLAB functions, whenever possible, rather than writing your own. If a MATLAB function is
built-in, then it has been written in C and is faster than anything you can do. Even if it is not, much
time has been spent optimizing the functions that come with MATLAB; you are unlikely to do better.
(2) Replace control flow instructions with vector operations. We have already discussed this topic at
length in Section 8.2. Here we will focus on some advanced techniques.
Of course, we should first determine how much CPU time is really being expended in our program
and that is the profile command. It will happily show you the percentage of CPU time spent in
each line of each function in your program! And it will return the results in a very readable fashion! The
statements
>> profile on
>> ..........
>> profile viewer
begin and end profiling and display the results in the Profiler window.
As a simple example of method (0), consider the function hilb on page 101. hilb local(2000) runs
over 300 times slower if the line H = zeros(n) is omitted.
Continuing with this example, currently the MATLAB function hilb is written as
We have put quickly and slowly in quotes because this is quite subjective. Remember that your time is
valuable: if it takes you longer to optimize your code than you will save in running it more quickly, stifle the urge
to muck around with it. Also remember that the amount of time it actually takes to optimize a code is usually a
factor of two or three or . . . longer than the time you think it will take before you get started.
113
8.5. Advanced Topic: Vectorizing Code
function H = hilb2(n)
J = 1:n; % J is a row vector
J = J(ones(n, 1),:); % J is now an n by n matrix with each row being 1:n
I = J0 ; % I is an n by n matrix with each column being 1:n
E = ones(n, n);
H = E./(I+J-1);
as can be seen by entering
>> edit hilb
In the past this code ran nearly 20 times as fast as hilb local. However, now hilb local they are
roughly comparable depending on the computer and operating system. The reason is that MATLAB
has greatly improved its handling of for and while statements. Thus, it is frequently not necessary to
convert simple loops into complicated vector code.
As a realistic example of method (2), suppose you have a large vector y which is the discretization of
a smooth function and you want to know some information about it. In particular, consider the inter-
vals in y where yi > R. What is the average length of these intervals and what is their standard devia-
tion? Also, only include intervals which lie completely within y (i.e., ignore any intervals which begin or
end y ). It is not difficult to write such a code using control flow statements:
114
8.5. Advanced Topic: Vectorizing Code
115
9. Sparse Matrices
Finally, the question remains: is the time savings significant? For large y the CPU time is reduced by
over 20 (but this can vary greatly depending on y and R ).
Note: In get intervals slow we did not preallocate the vectors yin and yout. Since we have no idea
how many intervals there are, we have no way to preallocate these vectors to a reasonable size.
We could preallocate them to a large size, say length(y)/4, and then strip out the unused ele-
ments at the end of the code. However, unless the number of intervals is in the tens of thousands,
this will probably not save any time.
profile Profile the execution time of a MATLAB code. This is very useful for improving the
performance of a code by determining where most of the CPU time is spent.
9. Sparse Matrices
Many matrices that arise in applications only have a small proportion of nonzero elements. For exam-
ple, if T Cnn is a tridiagonal matrix, then the maximum number of nonzero elements is 3n2. This
is certainly a small proportion of the total number of elements, i.e., n2 , if n is large (which commonly
means in the hundreds or thousands or . . . ).
For full matrices (i.e., most of the elements are nonzero) MATLAB stores all the elements, while for
sparse matrices (i.e., most of the elements are zero) MATLAB only stores the nonzero elements: their
locations (i.e., their row numbers and column numbers) and their values. Thus, sparse matrices require
much less storage space in the computer. In addition, the computation time for matrix operations is sig-
nificantly reduced because zero elements can be ignored.
Once sparse matrices are generated, MATLAB is completely responsible for handling all the details of
their use: there are no special functions needed to work with sparse matrices. However, there are a num-
ber of functions which are inappropriate for sparse matrices, and MATLAB generally generates a warning
message and refers you to more appropriate functions. For example, cond(S) has to calculate S1 , which
is generally a full matrix; instead, you can use condest which estimates the condition number by using
Gaussian elimination. You have two alternatives: first, use full to generate a full matrix and use the
desired function; or, second, use the recommended alternative function.
There are three common function in MATLAB for creating sparse matrices. The first is to use speye
to create a sparse identity matrix instead of using eye which creates a full identity matrix. The second is
to enter all the nonzero elements of S Cmn individually by
>> S = sparse(i, j, s, m, n)
where i and j are vectors which contain the row and column indices of nonzero elements and s is the
vector which contains the corresponding values. For example, the square bidiagonal matrix
n 2
n1 4 0
n2 6
S= .. ..
. .
2 2n + 2
0 1
116
9. Sparse Matrices
i j si,j i j si,j
1 1 n 1 2 2
2 2 n1 2 3 4
3 3 n2 3 4 6
.. .. .. .. .. ..
. . . . . .
n1 n1 2 n2 n1 2n + 4
n n 1 n1 n 2n + 2
A simple way to generate this matrix is by entering
>> S = sparse([1:n], [1:n], [n:-1:1], n, n) + ...
sparse([1:n-1], [2:n], [-2:-2:-2*n+2], n, n)
We could, of course, generate S using one sparse function, but it would be more complicated. The
above function is easier to understand, even if it does require adding two sparse matrices. Since the out-
put from this function is basically just the above table, it is difficult to be sure that S is precisely what is
desired. We can convert a sparse matrix to full by
>> full(S)
and check explicitly that S is exactly what is shown in the above matrix.
In addition, a full (or even an already sparse) matrix A can be converted to sparse form with all zero
elements removed by
>> S = sparse(A)
Finally, a zero mn matrix can be generated by
>> SZ = sparse(m, n)
which is short for
>> SZ = sparse([], [], [], m, n)
The third common function for generating sparse matrices is
>> S = spdiags(B, d, m, n)
which works with entire diagonals of S. B is a min{ m, n }p matrix and its columns become the di-
agonals of S specified by d Cp . (For example, if d = (0, 1)T then the first column of B contains the
elements on the main diagonal and the second column contains the elements on the diagonal which is one
above the main diagonal.) Thus, we can also generate the matrix S given above by
>> B = [ [n:-1:1] 0 [0:-2:-2*n+2] 0 ]
>> S = spdiags(B, [0 1] 0 , n, n)
Warning: Be Careful! The function spdiags is somewhat similar to diag but must be handled more
carefully. Note that the element b1,2 is 0, which does not appear in S. The difficulty is that
the number of rows of B is generally larger than the lengths of the diagonals into which the
columns of B are to be placed and so some padding is required in B. The padding is done so
that all the elements in the k th row of B come from the k th column of S.
For example, the matrix
0 0 6 0 0
1 0 0 7 0
S1 = 0 2 0 0 8
0 0 3 0 0
0 0 0 4 0
can be generated as a sparse matrix by
>> A = diag([1:4], -1) + diag([6:8], 2)
>> S1 = sparse(A)
or by
>> B = [ [1:4] 0; 0 0 [6:8] ] 0
>> S1 = spdiags(B, [-1 2], 5, 5)
In the latter case note that the columns of B have to be padded with zeroes so that each col-
umn has five elements, whereas in the former case the vector which becomes the particular
diagonal precisely fits into the diagonal. The element s1,3 of S1 contains the value 6. It ap-
pears in the 3rd row of B because it occurs in the 3rd column of S1. Note that the element bn,2
117
9. Sparse Matrices
118
10.1. Basic Functions
speye Generates a sparse identity matrix. The arguments are the same
as for eye.
sprand Sparse uniformly distributed random symmetric matrix; the ma-
trix can also be positive definite.
sprandn Sparse normally distributed random matrix.
sparse Generates a sparse matrix elementwise.
spdiags Generates a sparse matrix by diagonals or extracts some diagonals
of a sparse matrix.
full Converts a sparse matrix to a full matrix.
find Finds the indices of the nonzero elements of a matrix.
nnz Returns the number of nonzero elements in a matrix.
spfun( 0 <function name> 0 , A) Applies the function to the nonzero elements of A.
spy Plots the locations of the nonzero elements of a matrix.
spconvert Generates a sparse matrix given the nonzero elements and their
indices.
sprandsym Generates a sparse uniformly distributed symmetric random ma-
trix; the matrix can also be positive definite.
y 00 + y 0 y(1 y 2 ) = cos t ,
which is called Duffings equation. This ode has many different types of behavior depending on the values
of the parameters , , , and .
As written, this is not in the form of a first-order system. To transform it we define y1 = y and
y2 = y10 = y 0 so that
y10 = y2
y20 = y100 = y 00 = y1 (1 y12 ) y2 + cos t
or
0
y1 y2
= .
y2 y1 (1 y12 ) y2 + cos t
Note: This same trick can be applied to an nth order by defining y1 = y, y2 = y10 , y3 = y20 , . . . ,
0
yn = yn1 .
119
10.1. Basic Functions
Before discussing how to solve Duffings equation specifically, we discuss the functions which solve time-
evolution odes. To obtain a numerical solution to a time-evolution first-order ode system, enter
>> <ode solver>(<function handle>, tspan, y0)
or
>> [t, Y] = <ode solver>(<function handle>, tspan, y0)
or
>> sol = <ode solver>(<function handle>, tspan, y0)
First, we have to choose which ode solver to use; this is discussed in detail shortly. It would be possible
for MATLAB itself to decide which numerical method to employ. However, there are good reasons why
the decision should be left in the hand of the user.
Warning: Make sure you understand how to enter the name of the function handle. This is discussed at
length in Section 3.2, and we also briefly discuss it below.
All of the solvers use the same input and output arguments, which we now discuss. The input parame-
ters are:
function The name of the function handle that calculates f(t, y).
tspan The vector that specifies the time interval over which the solution is to be calculated. If this
vector contains two elements, these are the initial time and the final time; in this case the
ode solver determines the times at which the solution is output. If this vector contains more
than two elements, these are the only times at which the solution is output.
Note: the final time can be less than the initial time, in which case the trajectory is moving
backwards in time.
y0 The vector of the initial conditions for the ode.
If there are no output parameters, the individual elements of the solution, i.e., y1 (t), y2 (t), . . . , yn (t),
are plotted vs. t on a single plot. The circles on the trajectories show the actual times at which the solu-
tion is calculated.
If there are two output parameters, these are:
t The column vector of the times at which the solution is calculated.
Y The matrix which contains the numerical solution at the times corresponding to t. The first
column of Y contains y1 , the second column y2 , etc.
If there is one output parameter, then it is a structure. The output is now
sol.x The column vector of the times at which the solution is calculated.
sol.y The matrix which contains the numerical solution at the times corresponding to t.
There are seven distinct ode solvers which can be used, as shown in the table below. All these ode
solvers use an adaptive step size to control the error in the numerical solution. Each time step is chosen
to try to keep the local error within the prescribed bounds as determined by the relative error and the
absolute error tolerances (although it does not always succeed). That is, ei , which is the error in yi , is
supposed to satisfy
ei max{ RelTol |yi |, AbsTol(i) }
where the default value of RelTol is 103 and of the vector AbsTol is 106 for each element. (How-
ever, there is no guarantee that the error in the numerical calculation actually satisfies this bound.)
ODE Solvers
The t in [t, Y] is unrelated to the t argument in the function duffing.
We have capitalized the Y in [t, Y] to indicate that the output is a matrix whereas the argument y is a
vector in the function.
120
10.1. Basic Functions
It is up to you to decide which ode solver to use. As a general rule, unless you believe that the ode is
stiff (which we discuss in the next paragraph), try ode45 or ode113. For a given level of accuracy, these
methods should run reasonably fast. (Which one runs faster is very dependent on the ode.) If you know
(or believe) that the ode is stiff, or if these two non-stiff solvers fail, then try ode15s.
And what is a stiff ode? There is no precise definition. Instead, we say it is stiff if the time step re-
quired to obtain a stable and accurate solution is unreasonably small. The best way to explain this
rather vague impression is through some simple examples.
Consider the second-order time-evolution ode
with the initial conditions y(0) = 1 and y 0 (0) = 2 . The solution to this ode is
y(t) = c1 et + c2 e1000t
where
1 1
c1 = (1 2 ) and c2 = (10001 + 2 ) .
1001 1001
There are two time scales in this solution: there is a rapid decay due to the e1000t term and there is a
slow growth due to the et term. Initially, the time step will be very small so that the rapid decay is
calculated accurately (i.e., t 1/1000 ). However, soon it will be negligible and the time step should in-
crease so that it calculates the slow growth accurately (i.e., t 1 ). However, if a non-stiff solver, such
as ode45 or ode23, is used, the time step must always be very small. That is, it must accurately track
the rapidly decaying term even after this term has disappeared in the numerical solution. The reason
is that a numerical instability will cause the trajectory to blow up if the time step increases. However, if
a stiff solver is used, the time step can increase by many orders of magnitude when the rapidly decaying
term has disappeared.
The same is true for the ode
y 00 + 1001y 0 + 1000y = 0
whose solution is
y(t) = c1 et + c2 e1000t .
Initially, the time step will be very small so that the rapid decay is calculated accurately (i.e.,
t 1/1000 ). However, soon it will be negligible and the time step should increase so that it calculates
the slowly decaying mode accurately (i.e., t 1 ).
On the other hand, consider the ode
y 00 1001y 0 + 1000y = 0
whose solution is
y(t) = c1 et + c2 e1000t .
the time step must always be very small so that the rapidly growing mode e1000t is calculated accu-
rately (i.e., t 1/1000 ). Thus, this is not a stiff ode.
The above examples are very simple. They are only designed to show that an ode is stiff if there is a
rapidly decaying mode and any growth in the solution occurs on a much slower time scale. (This fre-
quently happens in chemical reaction models, where some reactions occur on a very fast time scale and
and other occur on a much slower time scale.) In the next subsection we discuss van der Pols equation, a
second-order ode which is either non-stiff or stiff depending on the value of one parameter. You can plot
the solution and observe the separation of the fast scale and the slow scale as this parameter increases.
One difficulty with a stiff ode solver is that you might have to supply the Jacobian of the ode yourself if
the ode is really nasty. The Jacobian of f(t, y) is the nn matrix
fi
J(t, y) = (t, y) ,
yj
121
10.1. Basic Functions
Any of the stiff methods can approximate this matrix numerically. However, if the ode is bad enough,
this may not be enough. You may have to calculate all these partial derivatives yourself and include them
in your function file. (We show an example of this later.)
The reason for this large choice of ode solvers is that some odes are very, very, very nasty. It is possible
that most of the ode solvers will fail and only one, or maybe two, will succeed. SAY MORE???
To conclude this subsection, we return to Duffings equation. Suppose we want to solve the ode for
t [0, 100] with initial conditions y = (2, 1)T and plot the results. Since this is a very well-behaved ode
for the parameters given, we can use ode45. The simplest approach is to use an anonymous function to
input the right-hand side.
>> alpha = 0.05;
>> beta = 1.0;
>> Gamma = 0.5;
>> omega = 1.0;
>> duffing a = @(t, y)[y(2) ; y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t)];
>> ode45(duffing a, [0 100], [2 1]);
(The a denotes the fact that duffing a is an anonymous function handle.) The solution will now be
plotted as y1 and y2 vs. t. (This plot is rather cluttered because, not only is the trajectory plotted,
but in addition markers are put at each of the points of the numerical solution.)
Warning: There are a number of parameters which are needed by the function and these must be de-
fined before the function is created. Also, the function handle duffing a will always use these
parameters, even if they are later changed.
Note: Since duffing a is already a function handle, we merely need to use its name as the first argument
to ode45.
To obtain complete control over what is plotted, you should let ode45 output the trajectory and do the
plots yourself. This is easily accomplished by changing the last line of the previous code to
>> [t, Y] = ode45(duffing a, [0 100], [2 1]);
>> figure(1)
>> subplot(2, 1, 1)
>> plot(t, Y(:,1))
>> subplot(2, 1, 2)
>> plot(t, Y(:,2))
>> figure(2)
>> plot(Y(:,1), Y(:,2))
This results in a plot of y vs. t and a separate plot of y 0 vs. t, so that both plots are visible even if
they have vastly different scales. There is also a separate plot of y 0 vs. y, which is called a phase plane.
The next simplest approach is to use a nested function, and so there must also be a primary function.
function duffing ode(alpha, beta, Gamma, omega, y0, final time)
ode45(@duffing n, [0 final time], y0);
%%%%% nested function follows
function deriv = duffing n(t, y)
deriv = [ y(2) ; y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ];
end
end
(The n denotes the fact that duffing n is a nested function.) Note that the parameters are input to
the primary function and so are immediately accessible to the nested function. Clearly, this second ap-
proach (of using a nested function) requires more coding that the first approach (of using an anonymous
function). However, the first approach only works if the right-hand side can be defined using one MAT-
LAB statement. If the right-hand side is more complicated, then a nested function is the simplest choice.
Note: Since duffing n is a function, and not a function handle, we have to include @ before the name
of the function.
The third, and oldest, approach is to create a separate function m-file (i.e., a primary function) which
calculates the right hand side of this ode system.
122
10.1. Basic Functions
123
10.2. Advanced Functions
124
10.2. Advanced Functions
odeset( 0 <Prop 1> 0 , Assigns values to properties; these are passed to the ode solver when it is
<Value 1>, ...) executed.
AbsTol The absolute error tolerance. This can be a scalar in which case it applies to all the
elements of y or it can be a vector where each element applies to the corresponding
element of y. (Default value: 106 .)
Events A handle to a function which determines when an event occurs.
Jacobian A handle to a function which returns the Jacobian.
JPattern A sparse matrix whose nonzero elements (which should be 1 ) correspond to the possi-
ble nonzero elements of the Jacobian. This is only used when the Jacobian is calculated
numerically, i.e., when the Jacobian property is not used.
OutputFcn A handle to a function which is called after each successful time step. For example, a
plot of the trajectory can be generated automatically as it is being calculated.
Useful MATLAB functions are:
0
odeplot 0 which generates a plot of time versus all the components of the trajectory,
i.e., t vs. y1 , y2 , . . . , yn ;
0
odephas2 0 which generates a plot of y1 vs. y2 , i.e., Y(:,1) vs. Y(:,2);
0
odephas3 0 which generates a plot of y1 vs. y2 vs. y3 , i.e., Y(:,1) vs. Y(:,2)
vs. Y(:,3).
It is possible to plot different components of y using OutputSel.
OutputSel A vector containing the components of Y which are to be passed to the function speci-
fied by the OutputFcn parameter.
Refine Refines the times which are output in t. This integer value increases the number of
times by this factor. (Default value: 1 for all ode solvers except ode45, 4 for ode45.)
RelTol The relative error tolerance. (Default value: 103 ).
Stats Whether statistics about the run are output on the terminal (value: 0 on 0 ) after the
trajectory is calculated or they are not (value: 0 off 0 ). (Default value: 0 off 0 .)
For example, if you want to use ode45 with the relative error tolerance set to 106 for Duffings equa-
tion, enter
>> params = odeset( 0 RelTol 0 , 1.e-6);
>> [t, Y] = ode45(duffing a, tspan, y0, params);
The trajectory will be more accurate but the function will run slower. If you also want the statistics on
the performance of the particular ode solver used, enter
>> params = odeset( 0 RelTol 0 , 1.e-6, 0 Stats 0 , 0 on 0 );
>> [t, Y] = ode45(@duffing a, tspan, y0, params);
and the number of successful steps, the number of failed steps, and the number of times f(t, y) was eval-
uated will be printed on the terminal. This might be useful in optimizing the performance of the ode
solver if the function seems to be running excessively slowly. For implicit methods where the Jacobian
needs to be calculated, the number of times the Jacobian was evaluated, the number of LU decompositions,
and the number of times the linear system was solved will also be returned.
The ode solver can also record the time and the location when the trajectory satisfies a particular con-
dition: this is called an event. For example, if we are calculating the motion of the earth around the sun,
we can determine the position of the earth when it is closest to the sun and/or farthest away; or, if we are
following the motion of a ball, we can end the calculation when the ball hits the ground or we can let it
continue bouncing. Enter
>> ballode
to see a simple example.
For example, suppose we want to record where and when a trajectory of Duffings equation passes
through y1 = 0.5. That is, we define an event to be whenever the first component of y passes
through 0.5 or +0.5. This can be done by modifying the primary function duffing ode and replac-
ing the ode45 statement by
125
10.2. Advanced Functions
126
10.2. Advanced Functions
The right-hand side can be coded as a nested function inside a primary function by
function vdp ode(mu, y0, final time)
ode45(@vdp n, [0 final time], y0);
%%%%% nested function follows
function deriv = vdp n(t, y)
deriv = [y(2); mu*(1-y(1) 2)*y(2)-y(1)];
end
end
This is not stiff unless is large. For example, let = 1 and solve the ode with initial conditions
y(0) = 1 and y 0 (0) = 0 for t [0, 100] using ode45. Then, plot the result and note the number of ele-
ments in t. Repeat this procedure using = 10 and increase the final time, if necessary, so that you still
see a few complete oscillations. Then let = 100, etc., until the time required to plot a few oscillations
becomes very large. Then use ode15s and note the huge difference in the time required.
There is no need to use the ode solver parameters JPattern or Jacobian in this example because this
ode is so nice. However, since they might be needed for a nastier ode, we include them by using
Vdp pattern = sparse([1 2 2], [2 1 2], [1 1 1], 2, 2);
params = odeset( 0 Jacobian 0 , @vdpj n, 0 JPattern 0 , Vdp pattern):
[t, Y] = <ode solver>(@vdp n, tspan, y0, opt);
where the Jacobian is calculated numerically using the nested function
function J = vdpj n(t, y)
% vdpj n: Jacobian for van der Pols equation
J = [ 0 1; -2*mu*y(1)*y(2)-1 mu*(1-y(1) 2) ];
end
for the elements determined by Vdp pattern. By the way, if we use the property JPattern but not
Jacobian then the Jacobian is calculated numerically just for the elements determined by the sparse ma-
trix.
Note: Plotting the trajectory by
plot(t, Y)
is not very instructive. Instead, use
subplot(2,1,1)
plot(t, Y(:,1))
subplot(2,1,2)
plot(t, Y(:,2))
Our final example is slightly more complicated. Suppose we kick a ball into the air with initial speed
s and at an angle of , and we want to follow its motion until it hits the ground. Let the x axis be the
horizontal axis along the direction of flight and z be the vertical axis. Using Newtons laws we obtain the
ode system
x00 = 0 and z 00 = g
where g = 9.8 meters/second is the acceleration on the ball due to the earths gravity. The initial condi-
tions are
x(0) = 0 , x0 (0) = s cos , z(0) = 0, and z 0 (0) = s sin
where we assume, without loss of generality, that the center of our coordinate system is the initial location
of the ball. We also want to determine four events in the balls flight: the highest point of the trajectory
of the ball and the time it occurs, the distance it travels and the time it hits the ground, and the x val-
ues and times when the ball reaches the height h > 0. But beware because the ball may never attain this
height!
Although these odes can be solved analytically (consult any calculus book), our aim is to give an ex-
ample of how to use many of the advanced features of MATLABs ode solvers. (If we would include the
effects of air resistance on the ball, then these odes would become nonlinear and would not be solvable
127
10.2. Advanced Functions
One complication with solving this system numerically is that we do not know when the ball will hit
the ground, so we cannot give the final time. Instead, we use a time, 10s/g which is much greater than
needed and we let the program stop itself when the ball hits the ground. In addition, we want the relative
error to be 106 . Finally, we want the trajectory (i.e., z vs. x ) to be plotted automatically.
The following is a completely self-contained example using nested functions.
function [times, values] = gravity ode(speed, angle, height)
% gravity ode: The trajectory of a ball thrown from (0,0) with initial
% speed and angle (in degrees) given.
% times: (1) = time ball at peak, (2) = time ball hits ground
% (3,4) = time ball attains height
% values: (1) = z value at peak, (2) = x value when ball hits ground
% (3,4) = x values when ball attains height
% Note: (3,4) will not be used if height > z value at peak
g = 9.8;
gravity init()
[t, Y, tevent, Yevent, index event] = ode45(@gravity, tspan, y0, params);
if length(tevent) == 2
times = tevent;
values = [Yevent(1,3) Yevent(2,1)];
else
times = tevent([2 4 1 3]);
values = [Yevent(2,3) Yevent(4,1) Yevent(1,1) Yevent(3,1)];
end
%%%%% nested functions follow
function gravity init
% gravity init: Initialize everything
tspan = [0 10*speed/g];
y0 = [ 0; speed*cos(angle*pi/180); 0; speed*sin(angle*pi/180) ];
params = odeset( 0 RelTol 0 , 1.e-6, ...
0
Events 0 , @gravity event, ...
0
Refine 0 , 20, ...
0
OutputFcn 0 , 0 odephas2 0 , ...
0
OutputSel 0 , [1 3]);
end
function deriv = gravity(t, y)
% gravity: Calculates the right-hand side of the ode
deriv = [y(2); 0; y(4); -g];
end
function [value, isterminal, direction] = gravity event(t, y)
% gravity event: determines the events
value = [y(3); y(3)-height; y(4)]; % z = 0, z-height = 0, z = 0
isterminal = [1; 0; 0]; % halt only when z = 0
direction = [-1; 0; -1]; % an event occurs when z or z decrease through 0
% or z-height passes through 0 in either direction
end
end
Note that the parameters g, speed, angle, and height do not need to be passed into the nested func-
tions. Similarly, tspan, y0, and params do not need to be passed out.
128
10.2. Advanced Functions
MATLAB also has the function ode15i which solves fully implicit odes. It is very similar to the func-
tions we have already discussed, but there is one important difference. Although it is a very powerful
function, we only provide a very simple example which uses it.
We consider a linear second-order ode in a neighborhood of a regular singular point. Consider the ode
where P (t), Q(t), and R(t) are polynomials with no common factors. The singular points of this
ode are the values of t for which P (t) = 0. If t0 is a singular point, it is a regular singular point if
limtt0 (t t0 )Q(t)/P (t) and limtt0 (t t0 )2 R(t)/P (t). A common ode of this type is Bessels equa-
tion
t2 y 00 (t) + ty 0 (t) + (t2 n2 )y(t) = 0 for t 0 (10.1)
where n is a nonnegative integer and the initial condition is given at t = 0. The solution is denoted by
Jn (t) and, for specificity, we will concentrate on n = 1. At t = 0 the ode reduces to y(0) = 0 and so
we require y(0) = 0. The free initial condition is y 0 (0) and for this example we choose y 0 (0) = 1.
If we write Bessels equation as
n2
1
y 00 (t) + y 0 (t) + 1 2 y(t) = 0 (10.2)
t t
we clearly have a problem at t = 0 and for t 0. The ode solvers we discussed previously can han-
dle (10.2) for t 1 with the initial conditions that y(1) and y 0 (1) are given. However, a completely
different method of solution is required for t 0 and the form (10.1) is preferred to (10.2).
When we convert Bessels equation to the first order system we again let y1 (t) = y(t) and y2 (t) = y 0 (t)
and leave the t2 in the numerator to obtain
0
y1 y2
=
t2 y20 ty2 (t2 1)y1
Previously, we have always written the first-order system as y0 = f(t, y), but this form has a problem
when t = 0. Instead, we write it as g(t, y, y0 ) = 0 so that
y10 y2
g(t, y, y0 ) = .
t2 y20 + ty2 + (t2 1)y1
Finally, we not only have to input the initial condition y(0) = (0, 1)T , but we also have to input
T
y0 (0) = y10 (0), y20 (0) . It is easy to calculate y10 (0) = y2 (0), but y20 (0) y 00 (0) is more complicated.
Differentiate (10.1) with respect to t to obtain
t2 y 0000 (t) + 5ty 000 (t) + (t2 + 3)y 00 (t) + 4ty 0 (t) + 2y(t) = 0 .
Now set t = 0 to obtain y 00 (0) = 0. We can solve Bessels equation for t [0, 10] by
>> g = @(t, y, yp) [yp(1)-y(2);t 2 *yp(2)+t*y(2)+(t 2 -1)*y(1)];
>> tspan = [0 10]
>> y0 = [0;1]
>> yp0 = [1;0]
>> [t,Y] = ode15i(g, tspan, y0, yp0)
>> plot(t, Y(:,1))
ode15i Stiff ode solver for the fully implicit ode f(t, y, y 0 ) = 0.
129
11. Boundary-Value Ordinary Differential Equations
d
y = f(x, y) for x [a, b]
dx
where y Rn but conditions are given at both ends of the interval. If the boundary conditions are sep-
arated, then k conditions are given at x = a and n k other conditions are given at x = b. If the
boundary conditions are non-separated, then the conditions at x = a and at x = b are related. To allow
any of these boundary conditions we write the boundary conditions as y(a), y(b) = 0 where Rn .
For simplicity, we will only consider two closely related second-order odes, i.e., n = 2. This example
should enable you to study any boundary-value ode. Consider the two nonlinear boundary-value ordinary
differential equations
d2 y dy
(x) + 2 (x) + ey(x) = 0 (11.1a)
dx2 dx
and
d2 y dy
(x) + 2 (x) + ey(x) = 0 (11.1b)
dx2 dx
for x [0, 1] where > 0. Our boundary conditions are
y(0)
y(0), y(1) = =0, (11.2)
y(1)
which are called Dirichlet boundary conditions. These two odes are quite simple, but also quite interesting
and challenging to solve for certain intervals in .
We could use the Neumann boundary conditions y 0 (0) = 4 and y 0 (1) = 7 by
0
y (0) 4
y(0), y(1) = =0. (11.3)
y 0 (1) + 7
Or we could use the mixed boundary conditions y(0) y 0 (0) = 1 and y(1) + 2y 0 (1) = 3 by
y(0) y 0 (0) 1
y(0), y(1) = =0. (11.4)
y(1) + 2y 0 (1) 3
The primary MATLAB function is bvp4c. However, the functions bvpinit and deval are also
needed. We solve the boundary value problem by
>> sol = bvp4c(<right-hand side>, <boundary conditions>, <initial guess>)
There are two functions we need to write: odefun is f(x, y) and bcfun is the boundary conditions. For
our example the ode given by
function yp = nlode(x, y)
global which ode eps
if which ode == 1
yp = [y(2); -eps*exp(y(1))-2*y(2)];
else
yp = [y(2); -(exp(y(1))+2*y(2))/eps];
end
where we use global to input which ode to use and . The boundary condition is given by
function bc = nlode bc(ya, yb)
bc = [ya(1); yb(1)];
130
11. Boundary-Value Ordinary Differential Equations
Since these boundary conditions are particularly simple, we also include the function
function bc = nlode bc2(ya, yb)
bc = [ya(1)-ya(2)-1; yb(1)+2*yb(2)-3];
for mixed boundary conditions (11.4). In addition, we have to choose an initial guess for y(x) using
bvpinit by either
>> bvpinit(x, y init)
or
>> bvpinit(x, <initial guess function>)
For example, if we want the initial iterate to be a parabola which is zero at x = 0 and 1 and has maxi-
mum value A then y(x) = y1 (x) = 4Ax(1 x) and y 0 (x) = y2 (x) = 4A(1 2x) then we can write
>> x = linspace(0, 1, 21);
>> solinit = bvpinit(x, @nlode y ic);
where nrode y ic is written as
function y ic = nlode y ic(x)
global A
y ic = [4*A*x.*(1 - x); 4*A*(1-2*x)];
The only alternative is to write
>> x = linspace(0, 1, 21);
>> y1 val = ???;
>> y2 val = ???;
>> solinit = bvpinit(x, [y1 val; y2 val]);
where y1 val and y2 val are scalar values. Thus the initial guess is y1 = y1 val*ones(size(x)) and y2
= y2 val*ones(size(x)). This is often unacceptable because constant initial guesses may be so far from
the solution that convergence cannot be obtained. What we would like to do is
>> x = linspace(0, 1, 21);
>> y1 = 4*A*x.*(1 - x);
>> y2 = 4*A*(1 - 2*x);
>> solinit = bvpinit(x, [y1; y2]); % WRONG
This fails because y1 and y2 must be scalar variables and not vectors. If you really, really need y1 and
y2 to be vectors, then do not use bvpinit. Instead, specify the structure solinit directly by entering
>> x = linspace(0, 1, 21);
>> y1 = 4*A*x.*(1 - x);
>> y2 = 4*A*(1 - 2*x);
>> solinit.x = x;
>> solinit.y = [y1;y2];
Warning: This is dangerous because future versions of Matlab might change the fieldnames of the struc-
ture solinit. However, it works for now.
We are finally ready to solve this ode by
%%%%% script m-file: nlode1 >> global which ode e
>> global A
>> which ode = 1;
>> A = 1;
>> e = 3;
>> x = linspace(0, 1, 21);
>> solinit = bvpinit(x, @nlode y ic);
>> sol = bvp4c(@nlode, @nlode bc, solinit);
The solution is contained in sol and is extracted by deval. For example, if xi = (i 1)x where
x1 = 0 and xn = 1 then we determine, and plot, the numerical solution y by
%%%%% script m-file: nlode2 >> xpt = linspace(0, 1, 101);
>> Ypt = deval(sol, xpt);
>> plot(xpt, Ypt(1,:), xpt, Ypt(2,:), 0 r 0 )
Having done all this work, we now combine everything into the function m-file nlode all to show how
much easier it is to use nested functions and to combine everything into one primary function.
131
11. Boundary-Value Ordinary Differential Equations
132
12. Polynomials and Polynomial Functions
example, when = 0.01 we have y 0 (0) 130 and when = 0.001 we have y 0 (0) 1300. In conclusion,
we want to remind you that for the odes we have discussed here almost any halfway reasonable initial
choice for the ode (11.1a) will converge to one of the two solutions and for the ode (11.1b) will converge to
the single solution. However, you might well find an ode for which this is not true.
Boundary-Value Solver
is represented by the vector q = (c1 , c2 , . . . , cn )T . You can easily calculate the roots of a polynomial by
>> r = roots(q)
Conversely, given the roots of a polynomial you can recover the coefficients of the polynomial by
>> q = poly(r)
Warning: Note the order of the coefficients in the polynomial. c1 is the coefficient of the highest power of
x and cn is the coefficient of the lowest power, i.e., 0.
The polynomial can be evaluated at x by
>> y = polyval(q, x)
where x can be a scalar, a vector, or a matrix. If A is a square matrix, then
is calculated by
>> polyvalm(q, A)
(See Section 15 for more details on this type of operation.)
A practical example which uses polynomials is to find the best fit to data by a polynomial of a partic-
ular degree. Suppose the data points are
(3, 2), (1.2, 1), (0, 0.5), (1, 1), (1.8, 2)
and
we want to find the best fit by a straight line. Defining the data points more abstractly as
(xi , yi ) i = 1, 2, . . . , n and the desired straight line by y = c1 x + c2 , the matrix equation for the
straight line is
x1 1 y1
x2 1 c1 y2
.
.. .. = .. .
. c2 .
xn 1 yn
133
12. Polynomials and Polynomial Functions
In general, there is no solution to this overdetermined linear system. Instead, we find the least-squares
solution c = (c1 , c2 )T by
>> xdp = [-3 -1.2 0 1 1.8];
>> ydp = [-2 -1 -0.5 1 2];
>> c = [xdp ones(n, 1)] \ ydp
We can plot the data points along with this straight line by
>> x = linspace(min(x), max(x), 100);
>> y = polyval(c, x);
>> plot(x, y, xdp, ydp, 0 o 0 )
Notation: When discussing interpolation at a point x with data points (xi , yi ) i = 1, 2, . . . , n , there
are too many xs and ys. To make it clear which are the data points and which are the evalu-
ation points, we use xdp and ydp for the data points, and x for evaluation points with values
y.
We can find the best fit by a polynomial of degree m < n, i.e., y = c1 xm + c2 xm1 + + cm+1 , by
calculating the least-squares solution to
Vc = y
where xm
1 x1m1 x1 1
c1
xm
2 xm1
2 x2 1 c2
V=
.. .. .. .. and c =
... .
. . . .
xm
n xm1
n xn 1 cn
The matrix V is called a Vandermonde matrix . The statement
>> V = vander(xdp);
generates the square Vandermonde matrix with m = n 1. To generate the n(m 1) Vandermonde
matrix we want, enter
>> V = vander(x)
>> V(: , 1:m-1) = [];
This entire procedure can be carried out much more easily by entering
>> q = polyfit(xdp, ydp, m-1)
where the third argument is the order of the polynomial (i.e., the number of coefficients in the polyno-
mial).
Warning: The Vandermonde matrix is approximately as badly conditioned as the Hilbert matrix
which was discussed in Section 5.2. For example, cond(vander([1 : 10])) = 21012 whereas
cond(hilb(10)) = 21013 .
You can also find a local maximum or minimum of the polynomial p(x) by finding the zeroes of p0 (x).
The coefficients of p0 (x) are calculated by
>> q deriv = polyder(q)
where q is the vector of the coefficients of p(x). You can also integrate a polynomial by
>> q int = polyint(q)
in which case the constant term is 0, or by
>> q int = polyint(q, c)
for some constant c in which case the constant
term is c.
Given a set of data points (xi , yi ) there is sometimes a need to estimate values that lie within these
data points (this is called interpolation) or outside them (this is called extrapolation). This estimation is
generally done by fitting data which is near the desired value to a polynomial and then evaluating this
polynomial at the value.
There are a number of functions to interpolate data points in any number
of dimensions. The simplest
function in one dimension to interpolate the points (xi , yi ) 1 i n is
>> y = interp1(xdp, ydp, x, <method>)
where x is a vector of the values to be interpolated, y is the vector of the interpolated values, and
<method> is an optional argument specifying the method to be used. One additional requirement for
this function is that the elements of x are monotonic, i.e., either all in increasing order or in decreasing
order, to make it easy for the function to determine which data points are near the desired value. Five
of the interpolation methods which can be used are the following:
0
nearest 0 : The interpolated value is the value of the nearest data point.
0
linear 0 : Linear splines are used to connect the given data points. That is, straight lines connect
134
12. Polynomials and Polynomial Functions
135
13. Numerical Operations on Functions
Polynomial Functions
interp1(x, y, xvalues, <method>) Interpolates any number of values using the given data
points and the given method.
interp2 Interpolates in two dimensions.
interp3 Interpolates in three dimensions.
interpn Interpolates in n dimensions.
pchip Cubic Hermite interpolation.
poly(<roots>) Calculates the coefficients of a polynomials given its roots.
polyder(q) Calculates the derivative of a polynomial given the vector of
the coefficients of the polynomial.
polyfit(x, y, n) Calculates the coefficients of the
least-squares
polynomial of
degree n which fits the data (xi , yi ) .
(If n = length(x) - 1 it calculates the unique polynomial of
lowest degree which passes through all the data points.)
polyint(q) Calculates the integral of a polynomial given the vector of
the coefficients of the polynomial with the constant value
being 0. An optional second argument is used to obtain a
different constant value.
polyval(q, x) Evaluates the polynomial p(x).
polyvalm(q, A) Evaluates the polynomial p(A) where A is a square matrix.
ppval evaluates the piecewise polynomial calculated by pchip or
spline.
roots(q) Numerically calculates all the zeroes of a polynomial given
the vector of the coefficients of the polynomial.
spline Cubic spline interpolation.
vander Generates the Vandermonde matrix.
136
13. Numerical Operations on Functions
137
13. Numerical Operations on Functions
is xmin = (.1324 . . . , 1.0627 . . .). We are not done since we still have to calculate g(xmin ). This is
2.4109 which is small but is it small enough? We can decrease the termination tolerance by
>> opt = optimset( 0 TolX 0 , 1.e-8, 0 TolFun 0 , 1.e-8)
>> xmin = fminsearch(f, [0 0], opt)
Since g(xmin ) = 2.31017 we can assume that we have found a zero of f.
MATLAB can also calculate definite integrals using three function. The first is quad which uses adap-
Rb
tive Simpsons method. To evaluate a f (x) dx by Simpsons method enter
>> quad(<function handle>, a, b)
The full argument list is
>> quad(<function handle>, a, b, tol, trace)
where tol sets the relative tolerance for the convergence test and information about each iterate is
printed if trace is non-zero.
The second is quadl which uses adaptive Gauss-Lobatto quadrature, which is a variant of Gauss
quadrature.
quadl uses the more accurate formula and so should require many fewer function evaluations. For ex-
ample, quad calculates the exact integral (up to round-off errors) for polynomials of degree five whereas
quadl calculates the exact integral (up to round-off errors) for polynomials of degree nine.
The third is quadgk which uses adaptive Gauss-Kronrod quadrature. This function is more general
than the previous two because it is much more general:
The interval can be half-infinite (i.e., a = or b = + ) or fully infinute ( a = and
b = + ).
In addition the integrand can have an integrable singularity.
For example, the error in
>> f = @(x) 1./(1 + x. 2);
>> quadgk(f, 0, inf)
is 8.88181016 (the actual value is 2 ) and the error in
>> g = @(x) exp(sqrt(x))/sqrt(x);
>> quadgk(g, 0, 1)
is 2.36701013 (the actual value is 2(e 1) ).
MATLAB can also calculate the double integral
Z xmax Z ymax
f (x, y) dxdy
xmin ymin
by
>> dblquad(<function handle>, xmin, xmax, ymin, ymax)
It can also calculate the triple integral
Z xmax Z ymax Z zmax
f (x, y, z) dxdy dz
xmin ymin zmin
by
>> triplequad(<function handle>, xmin, xmax, ymin, ymax, zmin, zmax)
138
14. Discrete Fourier Transform
where Z T
1
a0 = f (t) dt
T 0
Z T
2
ak = f (t) cos kt dt
T 0
Z T
for k N[1, ) .
2
bk = f (t) sin kt dt
T 0
The coefficients a0 , a1 , a2 , . . . and b1 , b2 , . . . are called the real Fourier coefficients of f , and ak and bk
are the coefficients of the k th mode. The power of the function f (t) is
1 T
Z
2
P = f (t) dt
T 0
The term power is a misnomer because the function f need not be related to a physical quantity for which
the power makes any sense. However, we will stick to the common usage.
To understand the physical significance of power, we begin with the definition of work. Consider a particle
~ . If the particle moves from the point P0 to P1 then the
which is under the influence of the constant force F
139
14. Discrete Fourier Transform
so that
1X
P = |a0 |2 + |ak |2 + |bk |2 .
2
k=1
|a0 |2 if k = 0
Pk = 1 2 2
2 |ak | + |bk | if k > 0
and the frequency of the k th mode is k/T cycles per unit time.
Since
eit + eit eit eit
cos t = and sin t = ,
2 2i
we can rewrite the real Fourier series as the complex Fourier series
X
1
ibk )e2ikt/T + 12 (ak + ibk )e2ikt/T
f (t) = a0 + 2 (ak
k=1
so that
X
f (t) = ck e2ikt/T for all t [0, T ] (14.2)
k=
where
c0 = a 0
)
ck = 21 (ak ibk ) (14.3)
for k > 0 .
ck = 21 (ak + ibk )
The coefficients . . . , c2 , c1 , c0 , c1 , c2 , . . . are called the complex Fourier coefficients of f , and ck and
ck are the coefficients of the k th mode. (Note that these Fourier coefficients are generally complex.) We
can also calculate ck directly from f by
Z T
1
ck = f (t)e2ikt/T dt for k = . . . , 2, 1, 0, 1, 2, . . .
T 0
Note that if f is real, then ck = ck (by replacing k by k in the above equation). The power of f (t)
is
X
P = |c0 |2 + |ck |2 + |ck |2
k=1
work done to the particle is F ~ q~r , where ~r is the vector from P0 to P1 . The power of the particle is the work
~ q~v where ~v = ~r/t.
done per unit time, i.e., F
Next, consider a charge q which is moving between two terminals having a potential difference of V . The
work done on the charge is W = qV = ItV , where I is the current and t is the time it takes for the charge to
move between the two terminals. If R is the resistance in the circuit, V = IR and the power is
W V2
= IV = I 2 R =
P = .
t R
Thus, if we consider f (t) to be the voltage or the current of some signal, the instantaneous power in the signal is
proportional to f 2 (t) and the average power is proportional to
1 T
Z
2
f (t) dt .
T 0
140
14. Discrete Fourier Transform
We can only calculate a finite number of Fourier coefficients numerically and so we truncate the infinite
series at the M th mode. We should choose M large enough that
M
X
f (t) ck e2ikt/T for all t [0, T ] .
k=M
M
X
f (tj ) = k e2iktj /T for j = 0, 1, 2, . . . , N 1
k=M
or, written as a first-order system,
M
X
fj = k e2ijk/N for j = 0, 1, 2, . . . , N 1 (14.4)
k=M
N 1
1 X
k = fj e2ijk/N for k = M, M + 1, . . . , M . (14.5)
N j=0
M
X
fFS (t) = k e2ikt/T for all t [0, T ] .
k=M
It is our responsibility (using our experience) to choose M large enough that f (t) fFS (t). Given
f = (f0 , f1 , f2 , . . . , fN 1 )T , the Fourier coefficients are calculated in MATLAB by
>> fc = fft(f)/N
where the coefficients of the discrete Fourier transform are contained in fc in the order
T
0 , 1 , . . . , M 1 , M , M , M +1 , . . . , 2 , 1 .
Note that tN is not used because f (tN ) has the same value as f (t0 ) and so does not provide us with an
independent equation.
141
14. Discrete Fourier Transform
>> f = N*ifft(fc)
and the order is changed by ifftshift
It is important to check the Fourier transform to make sure it returns the results we expect. We began
with the real trigonometric series (14.1) and derived the complex trigonometric series (14.2) from it. The
nonzero Fourier coefficients of f (x) = cos x = (eix + eix )/2 are a1 = 1 and c1 = c1 = 1/2, whereas the
nonzero Fourier coefficients of f (x) = sin x = (eix eix )/(2i) are a1 = 1 and c1 = i/2 but c1 = i/2.
The code
>> n = 9;
>> x = linspace(0, 2*pi, n+1);
>> x(n+1) = [];
>> c c = fft(cos(x));
>> d c = fftshift(c c);
>> c s = fft(sin(x));
>> d s = fftshift(c s);
>> ci c = ifft(cos(x));
>> di c = ifftshift(c c);
>> ci s = ifft(sin(x));
>> di s = ifftshift(c s);
returns the vectors
cc = (0, 4.5, 0, 0, 0, 0, 0, 0, 4.5),
dc = (0, 0, 0, 4.5, 0, 4.5, 0, 0, 0),
cs = (0, 4.5i, 0, 0, 0, 0, 0, 0, 4.5i),
ds = (0, 0, 0, 4.5i, 0, 4.5i, 0, 0, 0),
(i)
cc = (0, 0.5, 0, 0, 0, 0, 0, 0, 0.5),
(i)
dc = (0, 0, 0, 0, 0.5, 0, 0.5, 0, 0),
(i)
cs = (0, 0.5i, 0, 0, 0, 0, 0, 0, 0.5i), and
(i)
ds = (0, 0, 0, 0, 0.5i, 0, 0.5i, 0, 0).
Notice that fft and ifft both return the correct coefficients for cos x (up to the scaling of n ), but only
the fft returns the correct coefficients for sin x. Thus, the function fft is correct, but it multiplies the
coefficients by N .
Also, notice that fftshift correctly shifts the coefficients, whereas ifftshift does not but
ifftshift correctly shifts the coefficients back. That is, ifftshift is the inverse of fftshift so
ifftshift(fftshift(c s)) = c s.
Warning: One of the most common mistakes in using fft is forgetting that the input is in the order
f0 , f1 , f2 , . . . , fN 1
0 , 1 , . . . , M 1 , M , M , M +1 , . . . , 2 , 1 ,
not
M , M +1 , . . . , 2 , 1 0 , 1 , . . . , M 1 , M .
There is only one difficulty with our presentation. As we have already stated, the vector f has
N = 2M + 1 elements, which is an odd number. The Fast Fourier Transform (FFT, for short), which
is the method used to calculate the discrete Fourier coefficients by fft and also to recover the original
function by ifft, generally works faster if the number of elements of f is even, and is particularly fast if
it a power of 2.
The figure below shows the cputime needed to calculate fft(f) as a function of N . Since the verti-
cal axis is logarithmic, it is clear that there is a huge difference in the time required as we vary N .The
dashed lines show the minimum and maximum asymptotic times as cn log2 n.
For N to be even, we have to drop one coefficient, and the one we drop is M . Now
N = 2M
142
14. Discrete Fourier Transform
4
10
cpu time (seconds)
5
10
6
10
dashed lines are c*n*log2n; c = 2.7e09, 2.0e08
7
10
0 200 400 600 800 1000 1200 1400 1600 1800 2000
n
M
X 1
fFS (t) = k e2ikt/T for all t [0, T ]
k=M
N 1
1 X
k = fj e2ijk/N for k = M, M + 1, . . . , M 2, M 1 .
N j=0
143
14. Discrete Fourier Transform
144
14. Discrete Fourier Transform
>> sum(power0)
>> sum(powerpert)
The perturbed signal has about five times as much power as the original signal, which makes clear how
large the perturbation is.
Let us see if we can reconstruct the original signal by removing any mode whose magnitude is small.
By looking at the power plots, we see that the power in all the modes, except for those corresponding
to the spikes, have an amplitude / 0.1. Thus, we delete any mode of the perturbed Fourier spectrum,
i.e., fcpert, whose power is less than this value; we call this new Fourier spectrum fcchop. We then
construct a new signal ychop from this chopped Fourier spectrum and compare it with the original
unperturbed signal in
%%%%% script m-file: fft ex3
fcchop = fcpert; % initialize the chopped Fourier spectrum
ip = zeros(size(fcpert)); % construct a vector with 0s
ip(1:N/2) = ( powerpert > 0.1 ); % where fcchop should be
ip(N:-1:N/2 +2) = ip(2:N/2); % zeroed out
fcchop( find( ip) ) = 0; % zero out "small" modes
ychop = real( N*ifft(fcchop) ); % signal of "chopped" Fourier spectrum
figure(1)
plot(t, ychop, 0 b 0 )
figure(3)
plot(t, y0, 0 r 0 , t, ychop, 0 b 0 )
(which is contained in the accompanying zip file). ( ychop is the real part of N*ifft(fcchop) because,
due to round-off errors, the inverse Fourier transform returns a slightly complex result.) The result is
remarkably good considering the size of the perturbation.
If f (t) is an odd function in t, i.e., f (t) = f (t) for all t, then the real trigonometric series can be
simplified to
X 2kt
f (t) = bk sin
T
k=1
for t [0, T ] or for t [1/2 T, +1/2 T ]. Choosing the latter interval, we only need define f (t) for
t [0, 1/2 T ] and, additionally, state that it is an odd function. We discretize this infinite series by
n
X 2kt
fdst (t) = bk sin
T
k=1
for t [0, 1/2 T ] and we discretize this interval by 0 = t0 < t1 < < tn < tn+1 = 1/2 T where t =
1/ T /(n + 1). We immediately have f (t ) = f (t
2 0 n+1 ) = 0 so these two nodes are notneeded.
This leaves
us with the n coefficients bi i = 1, 2, . . . , n and the n data points ti , f (ti ) i = 1, 2, . . . n .
T
Defining the vectors b = (b1 , b2 , . . . , bn )T and f = f (t1 ), f (t2 ), . . . , f (tn ) , the MATLAB functions
dst and idst switch between them by
>> f = dst(b)
>> b = idst(f)
145
15. Mathematical Functions Applied to Matrices
Thus,
ea11
e a22
. . 0
eA = . .
ean1,n1
0 eann
The MATLAB function
>> expm(A)
calculates eA if A is a square matrix. (Otherwise, it generates an error message.)
A simple example where eA occurs is in the solution of first-order ode systems with constant coeffi-
cients. Recall that the solution of
dy
(t) = ay(t) for t 0 with y(0) = yic
dt
is
y(t) = yic eat .
Similarly, the solution of
y (t) y (t)
1 a11 a12 a1n 1
d y2 (t) a21 a22 a2n y2 (t)
. = . .. .. .. . for t 0 with y(0) = yic
dt .. .. . . . ..
yn (t) an1 an2 ann yn (t)
146
15. Mathematical Functions Applied to Matrices
Matrix Functions
147
15. Mathematical Functions Applied to Matrices
148
Appendix: Reference Tables
These tables summarize the functions and operations described in this tutorial. The number (or num-
bers) shown give the page number of the table where this entry is discussed.
Arithmetical Operators
+ Addition.(p. 7, 31)
- Subtraction.(p. 7, 31)
* Scalar or matrix multiplication.(p. 7, 31)
.* Elementwise multiplication of matrices.(p. 31)
/ Scalar division.(p. 7, 31)
./ Elementwise division of matrices.(p. 31)
\ Scalar left division, i.e., b\a = a/b. (p. 7)
\ The solution to Ax = b for A Cmn : when m = n and A is nonsingular this
is the solution Gaussian elimination; when m > n this is the least-squares ap-
proximation of the overdetermined system; when m < n this is a solution of the
underdetermined system.(p. 31, 83)
.\ Elementwise left division of matrices i.e., B.\A = A./B. (p. 31)
Scalar or matrix exponentiation.(p. 7, 31)
. Elementwise exponentiation of matrices.(p. 31)
Special Characters
149
Appendix: Reference Tables
Getting Help
Predefined Variables
ans The default variable name when one has not been specified.(p. 9)
pi . (p. 9)
eps Approximately the smallest positive real number on the computer such that
1 + eps 6= 1. (p. 9)
Inf (as in 1/0 ).(p. 9)
NaN Not-a-Number
(as in 0/0 ).(p. 9)
i 1 . (p. 9)
j 1 . (p. 9)
realmin The smallest usable positive real number on the computer.(p. 9)
realmax The largest usable positive real number on the computer.(p. 9)
Format Options
150
Appendix: Reference Tables
151
Appendix: Reference Tables
Input-Output Functions
csvread Reads data into MATLAB from the named file, one row per line of input.(p. 57)
csvwrite Writes out the elements of a matrix to the named file using the same format as
csvread. (p. 57)
diary Saves your input to MATLAB and most of the output from MATLAB to
disk.(p. 7)
fopen Opens the file with the permission string determining how the file is to be ac-
cessed.(p. 84)
fclose Closes the file.(p. 84)
fscanf Behaves very similarly to the C command in reading data from a file using any
desired format.(p. 84)
fprintf Behaves very similarly to the C command in writing data to a file using any de-
sired format.
It can also be used to display data on the screen.(p. 84)
input Displays the prompt on the screen and waits for you to enter whatever is de-
sired.(p. 10)
load Reads data into MATLAB from the named file, one row per line of input.(p. 57)
importdata Similar to load but there need not be an equal number of elements in each
row.(p. 57)
named file, one
row per line of
input.
print Prints a plot or saves it in a file using various printer specific formats.(p. 57)
152
Appendix: Reference Tables
Elementary Matrices
Specialized Matrices
153
Appendix: Reference Tables
Manipulating Matrices
cat Concatenates arrays; this is useful for putting arrays into a higher-dimensional
array.(p. 38)
clear Deletes a variable or all the variables. This is a very dangerous com-
mand.(p. 9)
diag Extracts or creates diagonals of a matrix.(p. 28)
fliplr Flips a matrix left to right.(p. 28)
flipud Flips a matrix up and down.(p. 28)
ind2sub Converts the indices of a matrix from column vector form to matrix form.(p. 99)
ipermute The inverse of permute. (p. 38)
permute Reorders the dimensions of a multidimensional array.(p. 38)
spdiags Generates a sparse matrix by diagonals.(p. 119)
repmat Tiles a matrix with copies of another matrix.(p. 28)
bsxfun Performs an operation on a matrix and a vector.(p. 28)
reshape Reshapes the elements of a matrix.(p. 28)
rot90 Rotates a matrix a multiple of 90 . (p. 28)
squeeze Removes (i.e., squeezes out) dimensions which only have one element.(p. 38)
sub2ind Converts the indices of a matrix from matrix form to column vector form.(p. 99)
triu Extracts the upper triangular part of a matrix.(p. 28)
tril Extracts the lower triangular part of a matrix.(p. 28)
[] The null matrix. This is also useful for deleting elements of a vector and rows or
columns of a matrix.(p. 28)
154
Appendix: Reference Tables
Two-Dimensional Graphics
Three-Dimensional Graphics
155
Appendix: Reference Tables
156
Appendix: Reference Tables
cumprod The cumulative product between successive elements of a vector or each column of
a matrix.(p. 37)
cumsum The cumulative sum between successive elements of a vector or each column of a
matrix.(p. 37)
errorbar Plots a curve through data points and also the error bar at each data point.(p. 58)
hist Plots a histogram of the elements of a vector.(p. )
max The maximum element of a vector or each column of a matrix. Alternately, if it
has two arguments, it returns a matrix of the same size which contains the larger
of the elements in each matrix.(p. 37)
min The minimum element of a vector or each column of a matrix.(p. 37)
mean The mean, or average, of the elements of a vector or each column of a ma-
trix.(p. 37)
norm The norm of a vector or a matrix.(p. 37)
prod The product of the elements of a vector or each column of a matrix.(p. 37)
sort Sorts the elements of a vector or each column of a matrix in increasing order(p. 37)
std The standard deviation of the elements of a vector or each column of a ma-
trix.(p. 37)
sum The sum of the elements of a vector or each column of a matrix.(p. 37)
157
Appendix: Reference Tables
Control Flow
158
Appendix: Reference Tables
Logical Functions
all True if all the elements of a vector are true; operates on the columns of a ma-
trix.(p. 99)
any True if any of the elements of a vector are true; operates on the columns of a ma-
trix.(p. 99)
exist False if this name is not the name of a variable or a file.(p. 99)
isequal Tests if two (or more) arrays have the same contents.(p. 99)
find The indices of a vector or matrix which are nonzero.(p. )
logical Converts a numeric variable to a logical one.(p. 99)
iscell True for a cell array.(p. )
ischar True if a vector or array contains character elements.(p. 99)
iscolumn True for a column vector.(p. 99)
isempty True if the matrix is empty, i.e., []. (p. 99)
isequal Tests if two (or more) arrays have the same contents.(p. 99)
isfield True if the argument is a structure field.(p. 46, 99)
isfinite Generates a matrix with 1 in all the elements which are finite (i.e., not Inf or
NaN ) and 0 otherwise.(p. 99)
isfloat True if a floating-point array.(p. 99)
isinf Generates a matrix with 1 in all the elements which are Inf and 0 other-
wise.(p. 99)
islogical True for a logical variable or array.(p. 99)
ismember Generates an array with 1 in all the elements which are contained in another ar-
ray.(p. 99)
isnan Generates a matrix with 1 in all the elements which are NaN and 0 other-
wise.(p. 99)
isnumeric True for a floating-point array.(p. 99)
isprime Generates an array with 1 in all the elements which are prime numbers. Only
non-negative integers are allowed in the elements.(p. 99)
isreal True for a real array, as opposed to a complex one).(p. 99)
isrow True for a row vector.(p. 99)
isscalar True for a scalar variable.(p. 99)
issparse True for a sparse array.(p. 99)
isstruct True for a structure array.(p. 99)
isvector True for a vector, as opposed to a matrix.(p. 99)
159
Appendix: Reference Tables
Debugging Commands
160
Appendix: Reference Tables
ode45 Non-stiff ode solver; fourth-order, one-step method for the ode y0 = f(t, y).
(p. 120)
ode23 Non-stiff ode solver; second-order, one-step method.(p. 120)
ode113 Non-stiff ode solver; variable-order, multi-step method.(p. 120)
ode15s Stiff ode solver; variable-order, multi-step method.(p. 120)
ode23s Stiff ode solver; second-order, one-step method.(p. 120)
ode23t Stiff ode solver; trapezoidal method.(p. 120)
ode23tb Stiff ode solver; second-order, one-step method.(p. 120)
ode15i Stiff ode solver; variable-order, multi-step method for the fully implicit ode
f(t, y, y0 ) = 0. (p. 129)
odeset Assigns values to properties of the ode solver.(p. 125)
Boundary-Value Solver
bvp4c Numerically solves y0 (x) = f(x, y) for x [a, b] with given boundary conditions
and an initial guess for y. (p. 133)
bvpset Assigns values to properites of bvp4c. (p. 133)
bvpinit Calculates the initial guess either by giving y directly or by using a function
y = initial guess function(x). (p. 133)
deval Interpolate to determine the solution desired points.(p. 133)
161
Appendix: Reference Tables
Matrix Functions
162
Solutions To Exercises
These are the solutions to the exercises given in subsections 1.9, 2.10, 3.6, and 4.7.
b) >> A = A - tril(A,-1)
d) >> S = sin(R)
e) >> r = diag(R)
b) >> z = 1 + x + x. 2 /2 + x. 6 /6
>> hold on
>> plot(x, z)
4.7.3) x is a row vector containing all the points at which the function is to be evaluated. c is
a column vector of the speeds. We can consider these to be the horizontal P and vertical
n
axes in two dimensions. We define h(x, c, t) = f (x ct) so that g(x, t) = k=1 h(x, ck , t).
meshgrid then turns these vectors into a mesh so that h(xj , ci , t) is evaluated by
h(X(i, j), C(i, j), t), where i refers to the vertical axis and j the horizontal one. (Since the
matrices X and C never change, they would not need to be actual arguments to h.) Thus,
h(t) (short for h(X, C, t) ) is a matrix whose (i, j)th element is f (xj ci t). We need to
multiply this by ai and then sum over i. This is done by multiplying the matrix R, whose
(i, j)th element is ai , elementwise by the matrix h(X, C, t). The sum function then adds all
the rows in each column.
165
Solutions To Exercises
166
ASCII Table
ASCII Table
Control Control
Octal Decimal Sequence Description Octal Decimal Sequence Description
000 0 @ Null character 100 64 @ AT symbol
001 1
A Start of header 101 65 A
002 2
B Start of text 102 66 B
003 3
C End of text 103 67 C
004 4
D End of transmission 104 68 D
005 5
E Enquiry 105 69 E
006 6
F Acknowledgment 106 70 F
007 7
G Bell 107 71 G
010 8
H Backspace 110 72 H
011 9
I Horizontal tab 111 73 I
012 10
J Line feed 112 74 J
013 11
K Vertical tab 113 75 K
014 12
L Form feed 114 76 L
015 13
M Carriage return 115 77 M
016
017
14
15
N
O
Shift out
Shift in
116
117
78
79
N
O
020 16 P Data link escape 120 80 P
021 17
Q Device control 1 (often XON) 121 81 Q
022 18
R Device control 2 122 82 R
023 19
S Device control 3 (often XOFF) 123 83 S
024 20
T Device control 4 124 84 T
025 21
U Negative acknowledgement 125 85 U
026 22
V Synchronous idle 126 86 V
027 23
W End of transmissions block 127 87 W
030 24
X Cancel 130 88 X
031 25
Y End of medium 131 89 Y
032 26
Z Substitute 132 90 Z
033 27
[ Escape 133 91 [ Left bracket
034 28
\ File separator 134 92 \ Back slash
035 29
] Group separator 135 93 ] Right bracket
036 30
Record separator 136 94 Caret
037 31
Unit separator 137 95
Underscore
040 32
Space 140 96 Opening single quote
041 33 ! 141 97 a
042 34 Double quote 142 98 b
043 35 # Numer sign 143 99 c
044 36 $ Dollar sign 144 100 d
045 37 % Percent 145 101 e
046 38 & Ampersand 146 102 f
047 39 Closing single quote (apostrophe) 147 103 g
050 40 ( Left parenthesis 150 104 h
051 41 ) Right parenthesis 151 105 i
052 42 * Asterisk 152 106 j
053 43 + Plus sign 153 107 k
054 44 , Comma 154 108 l
055 45 - Minus sign or dash 155 109 m
056 46 . Dot 156 110 n
057 47 / Forward slash 157 111 o
060 48 0 160 112 p
061 49 1 161 113 q
062 50 2 162 114 r
063 51 3 163 115 s
064 52 4 164 116 t
065 53 5 165 117 u
066 54 6 166 118 v
067 55 7 167 119 w
070 56 8 170 120 x
071 57 9 171 121 y
072 58 : Colon 172 122 z
073 59 ; Semicolon 173 123 { Left brace
074 60 < Less than sign 174 124 | Vertical bar
075 61 = Equal sign 175 125 } Right brace
076 62 > Greather than sign 176 126 Tilde
077 63 ? Question mark 177 127
? Delete
American Standard Code for Information Interchange (ASCII) specifies a correspondence between bit pat-
terns and character symbols. The octal and decimal representations of the bit patterns are shown along
with a description of the character symbol. The first 32 codes (numbers 031 decimal) as well as the last
(number 127 decimal) are non-printing characters which were initially intended to control devices or pro-
167
ASCII Table
vide meta-information about data streams. For example, decimal 10 ended a line on a line printer and
decimal 8 backspaced one character so that the preceding character would be overstruck. The control
sequence column shows the traditional key sequences for inputting these non-printing characters where
the caret ( ) represents the Control or Ctrl key which must be held down while the following key is
depressed.
168
Index
In this index MATLAB commands come first, followed by symbols, and then followed by the function m-files and
named script files which are coded in this tutorial and contained in the corresponding zip file. Only then does the
index begin with the letter A.
Note: All words shown in typewriter font are MATLAB commands or predefined variables unless it is specifically
stated that they are defined locally (i.e., in this document).
Note: If an item is a primary topic of a section, an appendix, or a subsection, this is indicated as well as the page
number (in parentheses).
Note: When an item appears in a box at the end of a subsection, or in the reference tables in the appendix, it is
underlined.
169
disp, 8, 9, 43, 84 gtext, 62, 63, 66, 67, 156
doc, 4, 15, 16, 17, 150 guide, 68, 73, 156
double, 47 heaviside, 13, 41, 151
drawnow, 52, 58, 155 help, 4, 15, 17, 100, 108, 150
dst, 145, 160 helpbrowser, 16, 150
echo, 104, 111, 160 hilb, 32, 33, 86, 113, 153
edit, 14, 15, 16, 154 histcounts, 55, 58, 155
eig, 32, 86, 90, 102, 158 histogram, 54, 58, 155
eigs, 87, 90, 158 hold, 50, 58, 155
else, 92, 95, 158 idst, 145, 160
elseif, 92, 93, 95, 158 if, 23, 91, 95, 158
end, 23, 91, 92, 94, 95, 108, 111, 158, 160 ifft, 142, 145, 160
error, 102, 111, 158, 160 ifftshift, 142, 144, 145, 160
errorbar, 55, 58, 155, 157 imag, 14, 151
eval, 111, 112, 113, 160 image, 65, 66, 156
events, 48 imagesc, 65, 66, 156
exist, 99, 159 importdata, 56, 57, 152
exp, 13, 14, 151 imread, 65, 66, 156
expm, 146, 147, 162 imshow, 65, 66, 156
expm1, 12, 13 imwrite, 65, 66, 156
eye, 20, 22, 153 ind2sub, 97, 99, 154
ezcontour, 60, 61, 155 inline, 41
ezcontour3, 60, 61, 155 input, 10, 104, 152
ezmesh, 60, 61, 155 int8, 47
ezplot, 53, 58, 155 int16, 47
ezplot3, 59, 61, 155 int32, 47
ezpolar, 54, 58, 155 int64, 47
ezsurf, 60, 61, 155 interp1, 134, 136, 162
factorial, 11, 13, 151 interp2, 136, 162
false, 93, 95, 153 interp3, 136, 162
fclose, 83, 84, 152 interpn, 136, 162
feval, 112, 113, 116, 160 inv, 29, 87, 90, 158
fft, 141, 145, 160 ipermute, 38, 154
fftshift, 141, 143, 145, 160 isa, 47, 48, 157
fieldnames, 46, 157 iscell, 99, 159
figure, 63, 66, 156 ischar, 99, 159
fill, 64, 66, 155 iscolumn, 99, 159
fill3, 64, 66, 155 isempty, 99, 106, 159
find, 96, 97, 99, 118, 119, 159, 161 isequal, 98, 99, 159
fix, 13, 151 isfield, 46, 99, 157, 159
fliplr, 26, 28, 154 isfinite, 98, 99, 159
flipud, 26, 28, 154 isfloat, 99, 159
floor, 13, 151 isinf, 99, 159
fminbnd, 137, 139, 161 islogical, 97, 99, 159
fminsearch, 137, 139, 161 ismember, 99, 159
fopen, 83, 84, 152 isnan, 99, 159
for, 23, 91, 95, 158 isnumeric, 99, 159
format, 10, 11, Subsect. 2.6 (32), 150 isprime, 99, 159
fplot, 42, 53, 66, 156 isreal, 99, 159
fprintf, 8, 43, 55, 83, 84, 152 isrow, 99, 159
fscanf, 55, 83, 84, 152 isscalar, 99, 159
full, 117, 119, 161 issparse, 99, 159
function, 99, 108, 111, 160 isstruct, 99, 159
function handle, 47 isvector, 99, 159
funm, 147, 162 keyboard, 104, 105, 160
fzero, 136, 137, 139, 161 lasterr, 112, 113, 116, 160
gca, 68, 156 legend, 62, 66, 156
gcf, 68, 156 length (number of elements in), 20, 22, 36, 97, 153
get, 67, 68, 156 linsolve, 78, 80, 158
getfield, 46, 157 linspace, 49, 58, 155
getframe, 76, 156 load, 16, 17, 55, 57, 65, 150, 152
ginput, 62, 66, 156 be careful, 56
global, 106, 111, 160 log, 13, 151
170
log10, 13, 151 qr, 89, 90, 158
log1p, 12, 13, 151 quad, 138, 139, 161
logical, 47, 98, 99, 159 quadgk, 138, 139, 161
loglog, 53, 58, 155 quadl, 138, 139, 161
logm, 147, 162 rand, 20, 22, 54, 81, 153
logspace, 58, 155 randi, 21, 22, 153
lookfor, 15, 17, 100, 108, 150 randn, 20, 22, 54, 153
lu, 88, 90, 158 randperm, 21, 22, 153
max, 34, 37, 157 rank, 89, 90, 158
mean, 35, 37, 157 rats, 82, 83, 154
mesh, 59, 61, 63, 155 real, 14, 151
meshgrid, 59, 60, 61, 155 rem, 13, 151
methods, 48 repmat, 26, 28
min, 35, 37, 157 reshape, 24, 26, 28, 154
mod, 13, 151 return, 102, 104, 105, 111, 160
movie, 76, 156 rmfield, 46, 157
movie2avi, 76, 156 rng, 20, 22, 153
nargin, 102, 111, 160 roots, 133, 136, 162
nargout, 102, 111, 160 rot90, 28, 154
ndgrid, 60, 61, 155 round, 13, 151
nnz, 118, 119, 161 rref, Sect. 5 (77), 80, 110, 158
norm, 36, 37, 88, 90, 102, 157, 158 save, 16, 17, 150
null, 88, 90, 158 saveas, 76, 156
num2str, 42, 43, 56, 84, 157 sec, 13, 151
numel, 22, 153 secd, 13, 151
ode15i, 129, 161 sech, 13, 151
ode15s, 120, 161 semilogx, 53, 58, 155
ode23, 120, 161 semilogy, 53, 58, 155
ode23s, 120, 161 set, 66, 67, 68, 156
ode23t, 120, 161 setfield, 46, 157
ode23tb, 120, 161 shg, 51, 58, 155, 156
ode45, 120, 161 sign, 13, 151
ode113, 120, 161 sin, 13, 151
odeset, 124, 125, 128, 132, 161 sind, 13, 151
ones, 20, 22, 153 single, 47
optimset, 136, 139, 161 sinh, 13, 151
orderfields, 46, 157 size, 20, 22, 153
orth, 88, 90, 158 sort, 36, 37, 44, 157
otherwise, 94, 95, 158 sparse, 116, 117, 119, 161
path, 101, 111, 154 spconvert, 118, 119, 161
pause, 52, 104, 111, 154 spdiags, 117, 119, 161
pchip, 135, 136, 162 differences from diag, 117
permute, 38, 154 speye, 119, 153, 161
persistent, 106, 111, 160 spfun, 119, 161
pinv, 82, 83, 89, 158 spline, 135, 136, 162
plot, 49, 50, 53, 58, 61, 134, 155 sprand, 118, 119, 153, 161
line properties, See Line properties sprandn, 118, 119, 153, 161
using set rather than plot, 75, 76 sprandsym, 118, 119, 153
plot3, 59, 61, 155 sprintf, 43, 157
pol2cart, 60, 61, 155 spy, 119, 161
polar, 54, 58, 155 sqrt, 13, 34, 151
poly, 133, 136, 162 sqrtm, 29, 146, 147, 162
polyder, 134, 136, 162 squeeze, 38, 154
polyfit, 134, 136, 162 sscanf, 43, 157
polyint, 134, 136, 162 std, 35, 37, 157
polyval, 133, 134, 136, 162 str2num, 43, 157
polyvalm, 133, 136, 162 strcmp, 92, 157, 158
ppval, 135, 136, 162 strfind, 96, 99, 157
primes, 24, 154 strtrim, 43, 157
print, 56, 57, 152 struct, 45, 46, 47, 157
prod, 37, 157 sub2ind, 97, 99, 154
profile, 113, 116, 150 subplot, 52, 58, 61, 155
properties, 48 sum, 37, 96, 157
171
surf, 59, 61, 63, 155 <=, 92, 158
svd, 89, 90, 158 >, 92, 158
switch, 23, 94, 95, 158 >=, 92, 158
different than in C, 94 ==, 92, 158
tan, 13, 151 =, 92, 158
tand, 13, 151
&, 93, 94, 95, 158
tanh, 13, 151 &&, 93, 94, 158
text, 62, 63, 66, 156 |, 93, 94, 95, 158
tic, 31, 152, 154 ||, 93, 94, 158
title, 54, 58, 67, 155 , 93, 94, 95, 105, 158
toc, 31, 152, 154
!, See factorial
toeplitz, 25, 28, 153 [], 23, 26, 28, 34, 154
tril, 25, 28, 154 @, 40
triplequad, 138 up-arrow key, 6, 7, 149
triu, 25, 28, 154
true, 93, 95, 153 Local m-files in companion zip file
type, 15, 16, 17, 100, 108, 150
uicontrol, 70, 73, 156 colormap example (modifying the colormap), 64
uint8, 47 duffing closure (Duffings ode), 123
uint16, 47 duffing ode (Duffings ode), 122
uint32, 47 duffing p2 (Duffings ode), 123
uint64, 47 fft ex1 (Fourier transform example), 144
uipanel, 70, 73, 156 fft ex2 (Fourier transform example), 144
uiresume, 73, 156 fft ex3 (Fourier transform example), 145
uiwait, 73, 156 fibonacci (recursive code for Fibonacci series), 111
vander, 134, 136, 153 fzero example (Calling fzero using a nested function),
varargin, 107, 111, 160 137
varargout, 107, 111, 160 get intervals fast (vector operations example), 116
vectorize, 41 get intervals slowly (non-vector operations
view, 59, 61, 155 example), 115
while, 23, 94, 95, 158 gravity ode (force of gravity example), 128
who, 16, 17, 150 hilb local (calculating Hilbert matrix), 101
whos, 16, 17, 150 hilb2 (calculating Hilbert matrix), 114
xlabel, 54, 58, 62, 67, 155 myheaviside (the Heaviside function), 103
xlim, 52, 58, 155 nested ex (example of nested functions), 109
xor, 93, 94, 95, 158 nlode (boundary value ode), 130
ylabel, 54, 58, 62, 67, 155 nlode1 (boundary value ode), 131
ylim, 53, 58, 155 nlode2 (boundary value ode), 131
zeros, 20, 22, 153 nlode all (boundary value ode), 132
zlabel, 59, 61, 67, 155 nlode bc (boundary conditions for nlode), 130
nlode bc2 (boundary conditions for nlode), 131
Symbols nlode y ic (initial conditions for nlode), 131
pause rippling (GUI example), 70
+, 7, 28, 31, 149, 152 pause rippling2 (GUI example), 72
exception to, 30 prealloc (example of preallocating arrays), 101
-, 7, 28, 31, 149, 152 rippling (plot surface in time), 69
*, 7, 28, 29, 31, 149, 152 running gaussians (plot Gaussians in time), 52
.*, 29, 31, 149, 152 sample movie (example making movie), 75
/, 7, 29, 31, 149, 152 spruce (example using optional arguments), 102
warning about matrix division, 29 vdp ode (van der Pols ode), 127
./, 29, 31, 149, 152
\, 7, 31, 77, 79, 82, 83, 149, 152 A
.\, 30, 31, 152
, 6, 7, 29, 31, 149, 152 AH , See Conjugate transpose
172
acot, 13, 151 Boundary-value ordinary differential equations, Sect. 11
acotd, 13, 151 (130), 133, 161
acoth, 13, 151 continuation method, 132
acsc, 13, 151 break, 94, 95, 158
acscd, 13, 151 bsxfun, 27, 28, 154
acsch, 13, 151 bvp4c, 130, 131, 133, 161
addframe, 76, 156 bvpinit, 131, 133, 161
addpath, 101, 111, 154 bvpset, 132, 133, 161
all, 36, 98, 99, 159
AND (logical operator), 93, 94, 95, 158 C
angle, 14, 151
Anonymous functions, See Function 15, 17, 150
ans, 8, 9, 150
CC,(programming language), 7, 23, 40, 43, 44, 46, 55, 66,
any, 36, 98, 99, 159 83, 84, 94, 106, 152, 157
Arithmetic progression, 22 C++ (programming language), 44, 112
Arithmetical operations, Subsect. 1.1 (6), Subsect. 2.4 Calculator, Subsect. 1.1 (6)
(28), 149 case, 94, 95, 158
+, 7, 28, 31, 149, 152 different than in C, 94
exception to, 30 Case sensitive, 9
-, 7, 28, 31, 149, 152 cat, 37, 38, 154
/, 7, 29, 31, 149, 152 Catching errors, 112
warning about matrix division, 29 caxis, 64, 66, 156
./, 29, 31, 149, 152 ceil, 13, 151
*, 7, 28, 29, 31, 149, 152 cell, 44, 46, 47, 157
.*, 29, 31, 149, 152 Cell array, 39, Subsect. 3.4 (43), 54
\, 7, 31, 77, 79, 82, 83, 149, 152 equal (are two cell arrays), 98
.\, 30, 31, 152 celldisp, 44, 46, 157
, 7, 29, 31, 149, 152 char, 47
. , 30, 31, 152 Character string, 7, 8, Subsect. 3.3 (42), 157
elementwise, 29, 30 appending to, 42
Array, Sect. 2 (17) comparing strings, 92
See also Matrix and Multidimensional arrays and concatenating, 42
Vector and Cell array converting to, 42, 43
equal (are two arrays), 98 executing, 111
ASCII character representation, 42, 62, 167 find substring in, 96
asec, 151 multiline, 42
asecd, 151 putting a number of strings in lexicographical ordering,
asech, 151 44
asin, 13, 151 TEX commands in, 62, 67
asind, 13, 151 chol, 85, 90, 158
asinh, 13, 151 Cholesky decomposition, 85
atan, 13, 151 clabel, 59, 61, 155
atan2, 13, 151 class, 47, 48, 157
atan2d, 13, 151 Class, Subsect. 3.5 (46)
atand, 13, 151 callback, 48
atanh, 13, 151 event, 48
Augmented matrix form, 7780 fundamental, 46
See also Matrix fundamental (table), 47
Average value, 35 handle, 48
avifile, 76, 156 listener, 48
axis, 52, 58, 61, 65, 155 subclass, 48
Axis user-defined, 47
changing numbers on, 67 value, 48
tick marks outside plot, 67 classdef, 48
clear, 8, 9, 12, 34, 154
B danger in using, 8
Clear (a figure), 63
Ball, 127128 See also clf and close
ballode, 125 clf, 63, 66, 156
Bessels equation, See Initial-value ordinary differential close, 63, 76, 156
equations Closure, 107, 123, 137
Binary format, 16, 56 Clown, 65
blanks, 43, 157 Colon operator, 19, Subsect. 2.2 (22), Subsect. 2.3 (23),
173
Colon operator (cont.) dblquad, 138, 139, 161
28, 149 dbquit, 104, 105, 160
possible floating-point errors in, 23, 49 dbstack, 105, 160
See also linspace dbstatus, 105, 160
Color map, 63 dbstep, 105, 160
colorbar, 63, 66, 155 dbstop, 105, 160
colormap, 63, 64, 66, 155 dbtype, 105, 160
Colors, See RGB components dbup, 105, 160
Command, 3 deal, 24, 154
See also Function Debugging m-files, See Function m-file and Script m-file
Comment character, 15, 149 demo, 3, 16, 17, 49, 61, 66, 150, 156
Complex conjugate, 14 Demonstration program, 3, 16, 61, 65
Complex numbers, 6, Subsect. 1.6 (13) det, 86, 90, 158
Conchoid of Nicodemes Determinant, 86
cond, 81, 85, 90, 158 deval, 131, 133, 161
condest, 85, 90, 158 diag, 24, 28, 154
Condition number, See Matrix Diagonals, See Matrix
conj, 14, 151 diary, 6, 7, 152
Conjugate transpose, 19 diff, 36, 37
See also Transpose Digits of accuracy, 10
Continuation (of a line), 15, 149 disp, 8, 9, 43, 84
Continuation method, 132 Discrete Fourier transform, See Fourier transform
continue, 94, 95, 158 Discrete sine transform, See Fourier transform
contour, 59, 61, 155 Display
Contour plot, 59 formatting the, Subsect. 1.4 (10)
contour3, 59, 61, 155 misinterpreting, Subsect. 2.6 (32)
contourf, 59, 61, 64, 155 suppressing, 7, 9, 18, 28, 149
Control flow, See Programming language variable, 8, 9, 84
cos, 13, 151 See also disp and fprintf
cos z, 14 doc, 4, 15, 16, 17, 150
cosd, 13, 151 Documentation (MATLAB), 16
cosh, 13, 151 Dot product, 30
cot, 13, 151 double, 47
cotd, 13, 151 drawnow, 52, 58, 155
coth, 13, 151 dst, 145, 160
CPU, 30 Duffings equation, See Initial-value ordinary
cputime, 30, 31, 152, 154 differential equations
csc, 13, 151
cscd, 13, 151 E
csch, 13, 151
csvread, 55, 57, 83, 152 ez , 14
csvwrite, 55, 57, 83, 152 Earth, 65
Cubic splines, See Interpolation echo, 104, 111, 160
cumprod, 36, 37, 157 edit, 14, 15, 16, 154
cumsum, 36, 37, 157 eig, 32, 86, 90, 102, 158
Cursor Eigenvalues, 32, 85, 86, 87, 90, 102
entering current position, 62 definition of, 86
Eigenvectors, 86, 87, 90, 102
D eigs, 87, 90, 158
else, 92, 95, 158
Data elseif, 92, 93, 95, 158
best polynomial fit to, 133 end, 23, 91, 92, 94, 95, 108, 111, 158, 160
closing files, 83 eps, 9, 10, 94, 150
manipulation, Subsect. 2.8 (34), 157 See also Machine epsilon
opening files, 83 Erase (a figure), 63
reading into MATLAB, 55, 57, 83, 118, 152 See also clf
writing from MATLAB, 55, 57, 83, 152 error, 102, 111, 158, 160
Data types, 40, Subsect. 3.5 (46) Error bars, 54, 55
fundamental errorbar, 55, 58, 155, 157
fundamental (table), 47 Euclidean length, See Length of a vector
dbclear, 105, 160 eval, 111, 112, 113, 160
dbcont, 105, 160 events, 48
dbdown, 105, 160 EXCLUSIVE OR (logical operator), 94, 95, 158
174
exist, 99, 159 fscanf, 55, 83, 84, 152
exp, 13, 14, 151 specifications (format), 83
expm, 146, 147, 162 full, 117, 119, 161
expm1, 12, 13 function, 99, 108, 111, 160
Exponentiation, 6, 7, 29 Function, 23, Subsect. 8.3 (99)
Extrapolation, 134 anonymous, Subsect. 3.1 (40), 45
See also Interpolation warning, 41
eye, 20, 22, 153 built-in, 11, 15, 16
ezcontour, 60, 61, 155 commands in, 105, 111, 160
ezcontour3, 60, 61, 155 comments in, 100
ezmesh, 60, 61, 155 conflict between function and variable name, 12
ezplot, 53, 58, 155 debugging, 103, 104
ezplot3, 59, 61, 155 definition line, 99
ezpolar, 54, 58, 155 differences from command, 3
ezsurf, 60, 61, 155 end statement, 108
ending, 108
F error, 102, 111, 158, 160
example using multiple input and output arguments,
factorial, 11, 13, 151 102
Factorial function, 11 function (required word), 99, 108, 111, 160
false, 93, 95, 153 inline, 41
FALSE (result of logical expression), 93 warning, 41
Fast Fourier transform, See Fourier transform input and output arguments, 99, 105
fclose, 83, 84, 152 grouping together, 107
feval, 112, 113, 116, 160 pass by reference, 100
fft, 141, 145, 160 pass by value, 100
fftshift, 141, 143, 145, 160 variable number of, 102
Fibonacci sequence, 110 name of, 14
Field, See Structure warning about user-defined m-files, 14
fieldnames, 46, 157 nested, 100, 108
figure, 63, 66, 156 order in which MATLAB searches for functions, 100,
fill, 64, 66, 155 110
fill3, 64, 66, 155 passing arguments indirectly, See Closure
find, 96, 97, 99, 118, 119, 159, 161 passing function name in argument list, Subsect. 3.2
Finite differences, 36 (41), 112, 113
fix, 13, 151 piecewise, 40
fliplr, 26, 28, 154 primary, 108
flipud, 26, 28, 154 private, 110
Floating-point numbers, 9, 23 return, 102, 104, 105, 111, 160
Floating-point operations, See Flops saving parameters in, 106107
floor, 13, 151 subfunctions in, 100, 108
Flops (fl oating-point operations), 30 Function handle, 40, 45
Flow of control, See Programming language function handle, 47
fminbnd, 137, 139, 161 Function m-file, Subsect. 8.3 (99)
fminsearch, 137, 139, 161 debugging, 103, 104
fopen, 83, 84, 152 names of, 14, 100
for, 23, 91, 95, 158 passing name into, 41
format, 10, 11, Subsect. 2.6 (32), 150 recursive, 110
Format options (in format command), 10, 11, 150 Functions (mathematical)
Format specifications (in fprintf, fscanf, sprintf, and See also Polynomials
sscanf), 83 common mathematical, Subsect. 1.5 (11)
Fourier series, Sect. 14 (139) definite integrals of, 138
complex, 140 hijacked, 110
real, 139 local minimum of, 137
Fourier transform, Sect. 14 (139) numerical operations on, 136, 139, 161
discrete, Sect. 14 (139), 145, 160 zeroes of, 136, 137
discrete sine, 145 funm, 147, 162
fast (FFT), 142 fzero, 136, 137, 139, 161
fplot, 42, 53, 66, 156
fprintf, 8, 43, 55, 83, 84, 152 G
printing a matrix, 84
specifications (format), 83 Gauss-Kronrod quadrature (for numerical integration),
Frequency, See Power 138
175
Gauss-Lobatto quadrature (for numerical integration), I
138
Gaussian elimination, 77, 81 I, See Identity matrix
gca, 68, 156 i, 6, 9, 150
gcf, 68, 156 Identity matrix, 20
Generalized eigenvalue problem, 86 See also eye
get, 67, 68, 156 idst, 145, 160
getfield, 46, 157 if, 23, 91, 95, 158
getframe, 76, 156 ifft, 142, 145, 160
ginput, 62, 66, 156 ifftshift, 142, 144, 145, 160
global, 106, 111, 160 imag, 14, 151
Gram-Schmidt algorithm, 89 image, 65, 66, 156
Graphical image, 65 imagesc, 65, 66, 156
export, 65 Imaginary numbers, 6, 9, 150
extensions, 65 importdata, 56, 57, 152
import, 65 imread, 65, 66, 156
show, 65 imshow, 65, 66, 156
Graphics, Sect. 4 (49) imwrite, 65, 66, 156
advanced techniques, Subsect. 4.3 (61), 156 ind2sub, 97, 99, 154
changing endpoints, 52 Inf, 9, 150
customizing lines and markers, 50 Initial-value ordinary differential equations, Sect. 10
demonstration, 49 (119)
handle, Subsect. 4.4 (66) Bessels equation, 129
holding the current plot, 50 Duffings equation, 119126
first-order system, 119
labelling, 6266
with constant coefficients, 146
text properties, 67
solvers, 120, 161
using TEX commands, 62, 67
absolute error, 120
multiple plots, 52
adaptive step size, 120
multiple windows, 63
events, 126
object, 66
ode15i, 129, 161
handle for an, 66
ode15s, 120, 161
printing, 56, 57, 152
ode23, 120, 161
properties, Subsect. 4.4 (66)
ode23s, 120, 161
saving to a file, 56, 57, 152
ode23t, 120, 161
three-dimensional, Subsect. 4.2 (59) ode23tb, 120, 161
two-dimensional, Subsect. 4.1 (49), 155 ode45, 120, 161
window, 49 ode113, 120, 161
Gravity, 127 passing parameters to, 123
gtext, 62, 63, 66, 67, 156 properties of, 125
GUI (Graphical User Interface), Subsect. 4.5 (68) relative error, 120
guide, 68, 73, 156 statistics for, 125
stiff, 121, 127
H Van der Pols equation, 126127
H
inline, 41
, See Conjugate transpose Inline functions, See Function, inline
Handle, See Function handle Inner product, 30
Handle graphics, See Graphics input, 10, 104, 152
heaviside, 13, 41, 151 int8, 47
Helix, 59 int16, 47
help, 4, 15, 17, 100, 108, 150 int32, 47
Help facility, Subsect. 1.8 (15) int64, 47
getting help, 17, 150 Integration, numerical, 138
searching for string, 15 interp1, 134, 136, 162
helpbrowser, 16, 150 interp2, 136, 162
Hermite polynomials, See Interpolation interp3, 136, 162
hilb, 32, 33, 86, 113, 153 interpn, 136, 162
Hilbert matrix, 32, 33, 81, 86, 90, 101, 134 Interpolation, 134, 135
function file for, 101, 113 cubic, 135
histcounts, 55, 58, 155 cubic splines, 135
histogram, 54, 58, 155 including first derivatives at the end points, 135
Histogram, 54 Hermite cubic interpolation, 135
hold, 50, 58, 155 how to do extrapolation, 135
176
Interpolation (cont.) log1p, 12, 13, 151
linear splines, 134 logical, 47, 95, 97, 98, 99, 159
inv, 29, 87, 90, 158 Logical (data type), 95
ipermute, 38, 154 LOGICAL AND (short circuiting logical operator), 93,
isa, 47, 48, 157 94, 158
iscell, 99, 159 LOGICAL OR (short circuiting logical operator), 93,
ischar, 99, 159 94, 158
iscolumn, 99, 159 Logical expression, 92
isempty, 99, 106, 159 result of, 93
isequal, 98, 99, 159 Logical functions, 99, 159
isfield, 46, 99, 157, 159 Logical operators, 94, 158
isfinite, 98, 99, 159 AND (&), 93, 94, 95, 158
isfloat, 99, 159 AND (short-circuit) (&&), 93, 94, 158
isinf, 99, 159 applied to matrices, Subsect. 8.2 (95)
islogical, 97, 99, 159 result of, 95
ismember, 99, 159 EXCLUSIVE OR (xor), 93, 94, 95, 158
isnan, 99, 159 NOT ( ), 93, 94, 95, 105, 158
isnumeric, 99, 159
OR (|), 93, 94, 95, 158
isprime, 99, 159 OR (short-circuit) (||), 93, 94, 158
isreal, 99, 159 loglog, 53, 58, 155
isrow, 99, 159 logm, 147, 162
isscalar, 99, 159 logspace, 58, 155
issparse, 99, 159 lookfor, 15, 17, 100, 108, 150
isstruct, 99, 159 lu, 88, 90, 158
isvector, 99, 159 LU decomposition, 88
J M
j, 6, 9, 150 M-files, 99
Java (programming language), 112 See also Function m-file and Script m-file
Machine epsilon (eps), 9, 150
K calculation of, 94
Mathematical functions, Subsect. 1.5 (11), 14, Subsect.
keyboard, 104, 105, 160 2.7 (34), 151
Keywords, 8 Matrix
Kill current statement, 15 as column vector, 24, 97
augmented, 7780
L is not a matrix, 78
Cholesky decomposition, 85
lasterr, 112, 113, 116, 160 condition number, 85
Left division, See \ approximation to, 85
legend, 62, 66, 156 defective, 86
Lemniscate of Bernoulli, 53 deleting rows or columns, 26
length (number of elements in), 20, 22, 36, 97, 153 determinant of, See Determinant
Length of a vector (i.e., Euclidean length), 36 diagonals of, 24, 117, 118
See also norm elementary, 22, 153
Life (Conways game of), 74 elementary operations, 153
Line properties, 61 empty, See null (below)
Linear splines, See Interpolation extracting submatrices, 23
Linear system of equations, Sect. 5 (77), Subsect. 5.3 full, 116
(81) generating, Subsect. 2.1 (18), Subsect. 2.3 (23)
least-squares solution, 82, 134 by submatrices, 21
overdetermined, Subsect. 5.3 (81), 134 individual elements, 20
solving by \, 29, 77, 82 Hermitian, 19
solving by linsolve, 78 Hilbert, See Hilbert matrix
solving by rref, Sect. 5 (77) identity, 20
underdetermined, Subsect. 5.3 (81) inverse of, 87
linsolve, 78, 80, 158 Jacobian, 121, 127
linspace, 49, 58, 155 lower triangular part of, 25, 88
load, 16, 17, 55, 57, 65, 150, 152 unit, 88
be careful, 56 LU decomposition, 88
log, 13, 151 manipulation, Subsect. 2.3 (23), 154
log10, 13, 151 masking elements of, 97
177
Matrix (cont.) Notation (for vectors and matrices), 5
maximum value, 35 null, 88, 90, 158
minimum value, 35 Null matrix, 26, 28, 154
multidimensional, Subsect. 2.9 (37) Null space, 88
null, 26, 28, 34, 154 num2str, 42, 43, 56, 84, 157
orthogonal, 89 numel, 22, 153
positive definite, 118
preallocation of, 20, 44, 101 O
pseudoinverse of, 82, 89
QR decomposition, 89 Ode, See Initial-value ordinary differential equations
replicating, 26 ode15i, 129, 161
reshaping, 24, 26 ode15s, 120, 161
singular, 79, 80, 85, 86 ode23, 120, 161
warning of, 87 ode23s, 120, 161
singular value decomposition, 89 ode23t, 120, 161
sparse, Sect. 9 (116), 161 ode23tb, 120, 161
specialized, 153 ode45, 120, 161
sum of elements, 35 ode113, 120, 161
SVD, See singular value decomposition (above) odeset, 124, 125, 128, 132, 161
symmetric, 19, 118 ones, 20, 22, 153
Toeplitz, 25 Operator precedence, Subsect. 2.5 (31)
tridiagonal, 85, 116 optimset, 136, 139, 161
unitary, 89 OR (logical operator), 93, 94, 95, 158
upper triangular part of, 25 orderfields, 46, 157
Vandermonde, See Vandermonde matrix Ordinary differential equations, See Initial-value
max, 34, 37, 157 ordinary differential equations and Boundary-value
Maximum value, 34 ordinary differential equations
mean, 35, 37, 157 orth, 88, 90, 158
Mean value, 35 Orthonormal basis, 88
Memory (of variables), 34 otherwise, 94, 95, 158
mesh, 59, 61, 63, 155 Outer product, 30
meshgrid, 59, 60, 61, 155 Overdetermined system, See Linear system of equations
methods, 48
min, 35, 37, 157 P
Minimum value, 35
mod, 13, 151 Parentheses, 9
Monotonicity, test for, 36 path, 101, 111, 154
Monty Python, 42 Path, See Search path
Moore-Penrose conditions, 82 pause, 52, 104, 111, 154
Moore-Penrose pseudoinverse, See Matrix, pchip, 135, 136, 162
pseudoinverse of permute, 38, 154
Mouse location, See ginput persistent, 106, 111, 160
movie, 76, 156 uses of, 106
movie2avi, 76, 156 Phase plane, See Plotting
Multidimensional arrays, Subsect. 2.9 (37) pi, 7, 9, 150
generate grid, 60 Piecewise polynomials, See Interpolation
permute order, 38 pinv, 82, 83, 89, 158
plot, 49, 50, 53, 58, 61, 134, 155
N line properties, See Line properties
using set rather than plot, 75, 76
NaN, 9, 150 Plot, generating a, See Graphics
nargin, 102, 111, 160 plot3, 59, 61, 155
nargout, 102, 111, 160 Plotting
ndgrid, 60, 61, 155 a curve, 49, 59
Newtons laws, 127 a function, 53
nnz, 118, 119, 161 a parametric function, 53
norm, 36, 37, 88, 90, 102, 157, 158 an implicit function, 53
Norm in polar coordinates, 54
matrix, 88 phase plane, 122
Frobenius, 88 pol2cart, 60, 61, 155
p -norm, 88 polar, 54, 58, 155
vector, 88 Polar coordinates, 54
NOT (logical operator), 93, 94, 95, 105, 158 poly, 133, 136, 162
178
polyder, 134, 136, 162 randn, 20, 22, 54, 153
polyfit, 134, 136, 162 Random matrix, 20, 25, 81, 119, 161
polyint, 134, 136, 162 Random numbers, 20
Polynomials, Sect. 12 (133), 162 Gaussian distribution, 20, 54
differentiating, 134 normal distribution, 20
evaluating, 133 pseudorandom numbers, 20
finding minimum and maximum of, 134 initial seed, 20
order of, 134 recommended procedure
representing by vector, 133 state, 20
roots of, 133 uniform distribution, 20, 54
polyval, 133, 134, 136, 162 randperm, 21, 22, 153
polyvalm, 133, 136, 162 rank, 89, 90, 158
Positive definite matrix, See Matrix Rank of matrix, 89
Power, 139, 140 Rational approximation to floating-point number, 82,
average, 140 154
definition of, 139 rats, 82, 83, 154
frequency of, 140 RCOND, 81, 86, 87
in each mode, 140 real, 14, 151
instantaneous, 140 realmax, 9, 150
spectrum, 140 realmin, 9, 10, 150
ppval, 135, 136, 162 Recursion, 110
Precedence, See Operator precedence Reduced row echelon form, 78
Predefined variables, See Variables round-off errors in, 80
Prime numbers, generating, 154 Relational operators, 92, 158
primes, 24, 154 <, 92, 158
Principles about computer arithmetic, 9, 11 <=, 92, 158
print, 56, 57, 152 >, 92, 158
Printing, See Display >=, 92, 158
prod, 37, 157 ==, 92, 158
Product =, 92, 158
dot, See Dot product
matrix, Subsect. 8.2 (95)
inner, See Inner product result of, 95
outer, See Outer product rem, 13, 151
profile, 113, 116, 150 Remainder, 13, 151
Programming language (MATLAB), Sect. 8 (91) repmat, 26, 28
flow of control, Subsect. 8.1 (91), 95, 158 Request input, 10
break out of, 94 reshape, 24, 26, 28, 154
continue loop, 94 return, 102, 104, 105, 111, 160
for loops, 91 Reverse two variables, 24
if statement, 91 RGB components (of a color), 63
switch statement, 23, 94, 95, 158 rmfield, 46, 157
different than in C, 94 randn, 20, 22, 54, 153
while loops, 94 rng, 20, 22, 153
needed less frequently, 95 roots, 133, 136, 162
properties, 48 rot90, 28, 154
Pseudoinverse, See Matrix round, 13, 151
Pseudorandom numbers, See Random numbers Round-off errors, Subsect. 1.3 (9), 11, 23, 25, 29, 33, 34,
Pythagorean theorem, 11 49, 80, Subsect. 5.2 (80), 81, 87
rref, Sect. 5 (77), 80, 110, 158
Q
S
qr, 89, 90, 158
QR decomposition, 89 save, 16, 17, 150
quad, 138, 139, 161 Save terminal commands, 6
quadgk, 138, 139, 161 Save work, 6
quadl, 138, 139, 161 saveas, 76, 156
Quadratic polynomial, roots of, 13 Scientific notation, 6
Quote mark, 7 Scope, See Variables
Script m-file, 14, 100, 104
R debugging, 103, 104
names of, 14
rand, 20, 22, 54, 81, 153 Search path, 100, 110
randi, 21, 22, 153 sec, 13, 151
179
secd, 13, 151 Surface plot, 59
sech, 13, 151 changing view, 59
semilogx, 53, 58, 155 filled-in, 59
semilogy, 53, 58, 155 wire-frame, 59
set, 66, 67, 68, 156 svd, 89, 90, 158
setfield, 46, 157 SVD, See Singular value decomposition
shg, 51, 58, 155, 156 switch, 23, 94, 95, 158
Short circuiting (logical operators), See LOGICAL
AND and LOGICAL OR T
sign, 13, 151
T
Simpsons method (of numerical integration), 138 , See Transpose
sin, 13, 151 tan, 13, 151
sin z, 14 tand, 13, 151
sind, 13, 151 tanh, 13, 151
single, 47 Taylor series expansion, 146
Singular value decomposition, 89 TEX, See Character string
sinh, 13, 151 text, 62, 63, 66, 156
size, 20, 22, 153 Text properties, 67
sort, 36, 37, 44, 157 Text window, 49
Sort numbers, 35 tic, 31, 152, 154
sparse, 116, 117, 119, 161 Time, See cputime and tic and toc
spconvert, 118, 119, 161 title, 54, 58, 67, 155
spdiags, 117, 119, 161 multiline, See Character string, multiline
differences from diag, 117 Title
speye, 119, 153, 161 for entire figure, 68
spfun, 119, 161 Toeplitz matrix, See Matrix
spline, 135, 136, 162 toeplitz, 25, 28, 153
Splines, See Interpolation toc, 31, 152, 154
sprand, 118, 119, 153, 161 Transpose, 19, 22, 153
sprandn, 118, 119, 153, 161 conjugate, 19, 22, 153
sprandsym, 118, 119, 153 Trigonometric functions, Subsect. 1.5 (11), Subsect. 2.7
sprintf, 43, 157 (34)
specifications (format), 83 tril, 25, 28, 154
spy, 119, 161 triplequad, 138
sqrt, 13, 34, 151 triu, 25, 28, 154
sqrtm, 29, 146, 147, 162 true, 93, 95, 153
squeeze, 38, 154 TRUE (result of logical expression), 93
sscanf, 43, 157 type, 15, 16, 17, 100, 108, 150
specifications (format), 83
Stairstep graph, 55 U
Standard deviation, 35
Statements uicontrol, 70, 73, 156
executing in text variables, 111 uint8, 47
rerunning previous, 10 uint16, 47
separating on a line, 7, 9, 18, 28, 149 uint32, 47
std, 35, 37, 157 uint64, 47
Step function, plotting a uipanel, 70, 73, 156
Stiff ode, 121, 127 uiresume, 73, 156
str2num, 43, 157 uiwait, 73, 156
strcmp, 92, 157, 158 Underdetermined system, See Linear system of
strfind, 96, 99, 157 equations
String, See Character string
strtrim, 43, 157 V
struct, 45, 46, 47, 157
Structure, 39, 44, 136 Van der Pols equation, See Initial-value ordinary
equal (are two structures), 98 differential equations
field, 44 vander, 134, 136, 153
sub2ind, 97, 99, 154 Vandermonde matrix, 134
Subfunctions, See Function m-file varargin, 107, 111, 160
subplot, 52, 58, 61, 155 varargout, 107, 111, 160
warning, 52 Variables, Subsect. 1.2 (7)
sum, 37, 96, 157 about, 9
surf, 59, 61, 63, 155 case sensitive, 9
180
Variables (cont.) X
conflict between variable and function name, 12
defined, 98 xlabel, 54, 58, 62, 67, 155
deleting, 9 xlim, 52, 58, 155
global, 105, 106 xor, 93, 94, 95, 158
inputting, 10
list of, 16 Y
loading, 16
local, 99, 105, 106 ylabel, 54, 58, 62, 67, 155
ylim, 53, 58, 155
logical, 97
modifying, 105, 106
Z
overwriting, 7
persistent, 106
zeros, 20, 22, 153
predefined, 7, 9, 150 zlabel, 59, 61, 67, 155
ans, 8, 9, 150
eps, 9, 10, 94, 150
i, 6, 9, 150
Inf, 9, 150
j, 6, 9, 150
NaN, 9, 150
overwriting, 7, 91
pi, 7, 9, 150
realmax, 9, 150
realmin, 9, 10, 150
reverse two, 24
saving, 16
saving local variables in functions, 106
scope of, 109
special cases of vectors or matrices, 7
static, 106
string, 7, Subsect. 3.3 (42)
See also Character string
typeless, 7, 105
valid names, 8
Vector
average value of elements, 35
column vs. row, 18
deleting elements, 26
equal (are two vectors), 98
generating, Subsect. 2.1 (18)
individual elements, 20
masking elements of, 97
maximum value, 34
mean value of elements, 35
minimum value, 35
preallocation of, 20, 44, 101
repeated elements, testing for, 36
sort elements, 35
standard deviation of elements, 35
sum of elements, 35
vectorize, 41
Vectorizing code, Subsect. 8.5 (113)
profile execution time, 113
view, 59, 61, 155
181
Index
182