## Are you sure?

This action might not be possible to undo. Are you sure you want to continue?

)

A MATLAB Tutorial

Ed Overman

Department of Mathematics

The Ohio State University

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 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 Commands . . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . . . 58

4.3 Advanced Topic: Commands . . . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . . . . . 78

5.2 Catastrophic Round-Off Errors . . . . . . . . . . . . . . . . . 81

5.3 Overdetermined and Underdetermined Linear Systems . . . . . . . . . . 82

6 File Input-Output . . . . . . . . . . . . . . . . . . . . . . 83

7 Some Useful Linear Algebra Functions . . . . . . . . . . . . . . . 85

8 Programming in MATLAB . . . . . . . . . . . . . . . . . . . 91

8.1 Flow Control and Logical Variables . . . . . . . . . . . . . . . . 91

8.2 Matrix Relational Operators and Logical Operators . . . . . . . . . . . 96

8.3 Function M-files . . . . . . . . . . . . . . . . . . . . . . 100

8.4 Odds and Ends . . . . . . . . . . . . . . . . . . . . . . 113

8.5 Advanced Topic: Vectorizing Code . . . . . . . . . . . . . . . . 114

9 Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . 117

10 Initial-Value Ordinary Differential Equations . . . . . . . . . . . . . 120

10.1 Basic Commands . . . . . . . . . . . . . . . . . . . . . . 120

10.2 Advanced Commands . . . . . . . . . . . . . . . . . . . . 125

11 Boundary-Value Ordinary Differential Equations . . . . . . . . . . . 131

12 Polynomials and Polynomial Functions . . . . . . . . . . . . . . . 135

13 Numerical Operations on Functions . . . . . . . . . . . . . . . . 138

14 Discrete Fourier Transform . . . . . . . . . . . . . . . . . . . 140

15 Mathematical Functions Applied to Matrices . . . . . . . . . . . . . 147

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 Commands . . . . . . . . . . . . . . . . . . . 157

Some Useful Functions in Linear Algebra . . . . . . . . . . . . . . . . 158

Logical and Relational Operators . . . . . . . . . . . . . . . . . . 158

Flow Control . . . . . . . . . . . . . . . . . . . . . . . . 158

Logical Functions . . . . . . . . . . . . . . . . . . . . . . . 159

Programming Language Functions . . . . . . . . . . . . . . . . . . 159

Debugging Commands . . . . . . . . . . . . . . . . . . . . . . 160

Discrete Fourier Transform . . . . . . . . . . . . . . . . . . . . 160

Sparse Matrix Functions . . . . . . . . . . . . . . . . . . . . . 160

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

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 function† because MATLAB’s 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 commands 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

†

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

Section 1 of this tutorial discusses how to use MATLAB as a “scalar” calculator. help command means to type these two words as written.. fine. This is how workbooks should be written: present some exercise for students to investigate. These three sections provide a “basic” introduction to MATLAB. “Play around” in- teractively and figure it out. investigate further and figure out why. you fell down a lot — and you looked pretty silly. this tutorial is not designed for “playing around”. Next. Maybe you mis- understood some MATLAB command. If an idea works. Section 6 is quite brief and discusses advanced commands to input data into MATLAB and output it to a file.) You have hopefully noticed that we skipped section 3. Don’t be afraid to make mistakes. You didn’t study Newton’s laws of motion and try to analyze the motion of a bicycle. In addition. you didn’t get videos from the library on how to ride a bicycle. MATLAB won’t call you an idiot for making a mistake. you will be able to set up and solve the matrix equation Ax = b where A is a square nonsingular matrix. (The basic commands are discussed in Section 4. This is how you should learn MATLAB. When you first learned to ride a bicycle. The following sections delve more deeply into particular topics. Finally. Typing >> help <command> or >> doc <command> gives you complete information about the command. When no solution exists. You just kept at it. It discusses a number of minor topics. we collect all these commands and put them in the appendix again boxed up by topic. Notation: help <command> means to enter whatever command you desire (without the braces). There are no hard and fast rules for figuring it out — try things and see what happens. possibly with the assistance of someone who steadied the bicycle and gave you a little push to get you started. the “best” approximation to a solution). 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.and three-dimensional plots. 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 discussed. or an infinite number to this linear system.e. it discusses how to calcu- late a least-squares solution (i. 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. and let them investigate it themselves. we try to separate these building blocks and put them in short subsections so that they are are easy to find and to understand. but it is a good way to document it. and Section 2 how to use it as a “matrix” calculator. Section 4 discusses how to plot curves in two and three dimensions and how to plot surfaces in three di- mensions. we have included it here. we collect all the commands discussed in a sub- section and put them in a box at the end along with a very brief discussion to make it easy to remember these commands. (Solutions are included.1. 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. one solution. Section 5 discusses how to find any and all solutions of Ax = b where A ∈ Cm×n need not be a square matrix. However. if it doesn’t. This is not the best way to learn MATLAB. there might be no solutions. 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. or maybe your idea needs some refinement. Warning: Usually we do not discuss the complete behavior of these commands. but only their most \use- ful" behavior. Following this. It is very ordered. it discusses how round-off errors can corrupt the solution. And these exercises should be interesting.they work. and how to determine if this is likely to occur. In addition. This tutorial is designed to be a reference manual that could be used alongside such a workbook — if only someone would write it. you didn’t take classes in how to ride a bicycle. But you kept at it until you didn’t fall down. Since they are useful in generating two. MATLAB has a HUGE number of commands and functions and this is one way to collect them for easy reference.) This is useful if the data is being shared 4 .

in Fortran). If a command has more than one use. Section 14 discusses the discrete Fourier transform and shows how it arises from the continuous Fourier transform. Thus. or a matrix. We distinguish them by using the lowercase x when it is a scalar or a vector. 2. Section 11 discusses how to use MATLAB to numerically solve boundary-value ordinary differential equations. a vector. Section 10 discusses how to use MATLAB to numerically solve initial-value ordinary differential equa- tions. called function m-files (which are similar to functions in C and to functions. These matrices could have been discussed in Section 2. matrix-vector multiplication is always written as A ∗ x and the inner product of the two vectors x and y is x 0 *y. Since the basic data ele- ment of MATLAB is a matrix. and finding their zeroes. Section 15 discusses how to apply mathematical functions to matrices.. can represent any number of types of data. Probably the most useful of these is calculating some or all of the eigenvalues of a square matrix. In a linear algebra setting we always define x to be a column vector. e. 5 . Polynomials and piecewise polynomials can also be used to interpolate data. matrices where most of the elements are zero). and integrals of functions. Notation: A variable. This tutorial closes with an index. Only then does the alphabetical index begin (which again contains all the MATLAB commands). All the MATLAB commands discussed here are listed at the beginning of the index. Section 13 discusses how to numerically calculate zeroes. Section 9 discusses how to generate sparse matrices (i. when it is worthwhile the time and storage saved can be boundless. fol- lowed by all the symbols.between various computer programs and/or software packages. you can code a complicated sequence of statements such that all these statements as well as all the the variables used by these commands are hidden and will not affect the remainder of your MATLAB session. extrema. and the uppercase X when it is a matrix. Section 8 discusses MATLAB as a programming language — a very “baby C”. more generally subprograms. 2. this programming language is very simple to learn and to use. 3) or column vectors (1. x1 y1 + x2 y2 + · · · + xn yn (where “ 0 ” is the MATLAB command to take the transpose of a real vector or matrix). i. We also provide an example which shows how to recover a simple signal which has been severely corrupted by noise. in MATLAB vectors can be either row vectors. It is designed to help in finding things that are “just on the tip of your tongue”. There is one appendix which collects all the commands discussed in this tutorial and boxes them up by topic. Finally.. The only way to pass data into and out of these functions is through the argument list.g.e. when it does we discuss in detail what to do and provide a num- ber of examples. Most of this discussion focuses on writing your own MATLAB commands. then followed by a list of all the script and function m-files which are in the companion zip file. Using these functions. but we felt that it added too much complexity at too early a point in this tutorial. Section 7 discusses a number of commands which are useful in linear algebra and numerical linear alge- bra. such as x. 3)T (where “ T ” is the transpose of a vec- tor or matrix). (1.. Also.e. for example. Unless the matrix is very large it is usually not worthwhile to gener- ate sparse matrices — however. Section 12 discusses how to numerically handle standard polynomial calculations such as evaluating polynomials. differentiating polynomials. but usually it represents a scalar. This section is divided up into a “basic” part and an “advanced” part. it might appear in two or more boxes. It often requires very little effort to solve even complicated odes.

1. Scalar Calculations

1.1. Simple Arithmetical Operations

**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

2×10−20 by

ˆ

>> 2*10 -20

ˆ

MATLAB, however, uses “e” to represent “10 ” so that MATLAB displays

2.0000e-20

ˆ

The “standard” way to input 2×10−20 is as 2e-20 or 2E-20 or 2.e-20 or 2.E-20 (even

2.0000000e-00020 is acceptable).

Warning: 10−20 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 5×1030 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 5×1030i ). 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

a+b Addition. a/b Division.

a-b Subtraction. a\b Left division, (this is exactly the same as

a*b Multiplication. b/a ).

a b Exponentiation (i.e., ab ).

ˆ

diary Saves your input to MATLAB and most of the output to disk. This command toggles

diary on and off. (If no file is given, it is saved to the file diary in the current direc-

tory.)

diary on turns the diary on.

diary off turns the diary off.

diary 0 <file name> 0 saves to the named file.

↑ 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 command 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 commands will be executed. Nothing will be printed out because semicolons follow each

command. 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 1×1. 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

7

1.2. Variables

**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

>> 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

**And now for something completely different
**

------------------------------------------

(The command fprintf, which will be discussed in Section 6, allows much finer formatting of variables.)

Note: When disp displays a variable or an array or an expression, it follows with a blank line. However,

when it displays a string or a string variable, it does not.

Incidentally, a valid name for a MATLAB variable is a character string containing letters (upper or

lower case), digits, and underscores where the first character must be a letter. The maximum length of a

name is too long to worry about. However, there are a few names which are reserved because they have

special meanings. The reserved words, called keywords, are

break continue for otherwise spmd

case else function parfor switch

catch elseif global persistent try

classdef end if return while

**(Of course, you can still use End or END — but you probably shouldn’t.)
**

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

8

You can also type nan. For example.. . pi π.3. . disp(X) Displays a variable (including an array) or a string without printing the variable name or ans. The results appear on the screen. For example. This is “approximately” the smallest positive real number that can be represented on the computer (on some computer realmin/2 returns 0 ). and then 1 is subtracted from the result. 1. real numbers) correctly. To delete a variable. the number has to be truncated. when we enter >> (1 + . 9 .e. in MATLAB 1 + 0. computers cannot store most floating-point numbers (i. many characters (but this is certainly “overkill”). Separates multiple statements on the same line. must start with a letter. About Variables Variables: are case sensitive (so xa is not the same as Xa ). the fraction 1/3 is equal to the real number 0. on our computer 1 + 1e-40 is not.1 is clearly greater than 1. .3333 . This is “approximately” the largest positive real number that can be represented on the computer (on most computer 2*realmax returns Inf ). realmin The smallest “usable” positive real number on the computer. When this ends a MATLAB command. Round-off Errors The most important principle for you to understand about computers is the following. Since a computer cannot store this infinite sequence of threes.1000 as expected. Inf ∞ (as in 1/0 ). To see this. multiply. type it alone on a line. eps Approximately the smallest positive real number on the computer such that 1 + eps 6= 1 . and can then be followed by any number of letters. type clear <variable>.1) . . realmax The largest “usable” positive real number on the computer. Computers cannot add. or divide correctly! Computers do integer arithmetic correctly (as long as the numbers are not too large to be stored in the computer). You can also type inf. Round-off Errors you will delete all the variables you have created in the workspace! Predefined Variables ans The default variable name when one has not been specified. 1. NaN Not-a-Number (as in 0/0 ). numbers. can contain up many. do not need to be declared or typed. however. However.3. This is a very dangerous command | use it at your own risk. subtract. eps is “close to” the difference between the exact number 1/3 and the approximation to 1/3 used in MATLAB. To display a variable. Principle 1.1 we obtain 0. the result is not printed on the screen. √ i √−1 .1. 1 + eps is the smallest floating-point number after 1 which can be stored precisely in the computer. Note: MATLAB guarantees that the expression in parentheses is evaluated first. and/or underscores (so z 0 is allowed). j −1 (the same as i because engineers often use these interchangeably). This can also separate multiple statements on the same line.

Alternatively. on a Mac or a PC use the copy command in the menu. ( n (1/3) ) 3 . You should be able to rerun the last statement executed without having to retype it by us- ing the up-arrow key. However.e-40.n ˆ ˆ MATLAB returns -1. enter >> n = input( 0 n = 0 ). Formatting Printing However. You can easily rerun this line for different values of n (as we described above) and explore how round-off errors can affect simple expressions.) What is not computer dependent is that this leads to errors in numerical calculations. Note: You can input a character string in two ways: >> str = input( 0 input string: 0 ). Warning: eps and realmin are very different numbers. for example. if you want to try some different values of n in experimenting with the expression (n1/3 ) − n. ( n (1/3) ) 3 . 1. 1. If you obtain 0.4. if you type 1/3 in MATLAB the result is only accurate to approximately this number of digits.4.. (On our computer it is 16.n ˆ ˆ The argument to the command input is the string which prompts you for input. the semicolon keeps the result of this command from being printed out.1 ˆ returns 0 is computer dependent. 0 Upper class twit of the year 0 or >> str = input( 0 input string: 0 . when we enter >> (1 + 1. whereas eps is approximately the small- est positive number on the computer such that 1 + eps 6= 1. For ex- 3 ample. which displays a prompt on the screen and waits for you to enter some input from the keyboard. use the format command in MATLAB.7764e-15 rather than the correct result of 0. The smallest positive integer n for which >> (1 + 10 (-n)) . and the input is stored in the variable n.1 MATLAB returns 0 rather than 1. 0 s 0 ). For example. For example.e-40) . in Unix enter p. when we enter >> n = 5. You do not see the decimal representation of 1/3 to this number of digits because on start-up MATLAB only prints the result to four decimal digits — or five significant digits if scientific notation is used (e. realmin is approximately the smallest positive number that can be represented on the computer.) Request Input input( 0 <prompt> 0 ) Displays the prompt on the screen and waits for you to input whatever is de- sired. and then enter. Type >> log10(1/eps) and remember the integer part of this number. 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. the calculation 1/30000 is displayed in sci- entific notation). Use 10 . Formatting Printing 3 The reason that (n1/3 ) − n can be nonzero numerically is that MATLAB only stores real numbers to a certain number of digits of accuracy. One command which is occasionally useful when you are just “playing around” is the input command. ( eps/realmin is larger than the total number of atoms in the known universe. This is approximately the maximum number of dig- its of accuracy of any calculation performed in MATLAB. try some different values of n. you will see in Section 5.2 that there are simple examples where this can lead to very incorrect results. ˆ Note: It might not seem important that MATLAB does not do arithmetical operations precisely.g. To change how the results are printed out. The optional second argument of “ 0 s 0 ” allows you to enter a string (including spaces) without using quote marks.

n) and them multiplying all its elements together by prod([1:n]). 1 .1102e-16. The relative error in the calculation of ex − 1. there are corresponding functions which are evaluated in degrees. For example. Almost all the functions shown here are built-in functions. MATLAB tries to calculate the correct result. which is calculated by >> factorial(n) Note: This function is actually calculated by generating the vector (1. format short g Results are printed in the best of either format short or format short e.. 11 . format long g Results are printed in the best of either format long or format long e. As an example. Most are entered exactly as you would write them mathematically. it is very likely that the number or numbers should be zero. (exp(x) . i. format long e Results are printed in scientific notation to approximately the maximum number of digits of accuracy in MATLAB. Common Mathematical Functions each of these six format functions and then type in 1/3 to see how the result is printed out. Sometimes these errors are small and unimportant — other times they are very important. try >> th = input( 0 angle = 0 ).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 . th = 40. (We discuss the colon operator in Section 2. Clearly. enter >> deg = pi/180. format long Results are printed to approximately the maximum number of digits of accuracy in MATLAB. 1. Note: If you obtained zero for the above calculation. Obviously. the result is supposed to be zero since. the trig functions are evaluated in radians.. they are coded in C so they execute very quickly. 1 . from the Pythagorean theorem cos2 θ + sin2 θ = 1 for all angles θ.e. The one exception is the factorial function. but it cannot quite. . all the numbers entered into this calculation are “reasonable” and the result is approximately eps. It is up to you to interpret what MATLAB is trying to tell you. format short e Results are printed in scientific notation using five significant digits.2. i. . MATLAB has introduced two functions to reduce round-off errors. .) There is an important principle to remember about computer arithmetic in MATLAB. Format Options format short The default setting. As is common in programming languages. >> sin(3) >> exp(2) >> log(10) return exactly what you would expect. 1! 2! 3! 1! 2! 3! † Be sure to define deg = pi/180 beforehand. n! = 1 · 2 · 3 · · · · · n.( cos(th*deg) 2 + sin(th*deg) 2 ) ˆ ˆ The result is 1. ˆ There are a number of occasions in this overview where we reiterate that MATLAB cannot usually cal- culate results exactly.5.e. That is. 2. 1. Common Mathematical Functions MATLAB contains a large number of mathematical functions. However.1)/exp(x) can be very large when x 1 since x2 x3 x2 x3 x x ex − 1 = 1+ + + + ··· − 1 = + + + ··· . Principle 1.( cosd(th) 2 + sind(th) 2 ) ˆ for various angles.5. In fact.† Some of these calculations should be nonzero. .

For example.1 = 9. 1. 1 2 3 4 which is evaluated by log1p(x). its complaint is that you are asking for the value of the third element of the vec- tor sin (which only has one element). suppose you enter >> sin = 20 by mistake (possibly you meant bin = 20 but were thinking about something else). because it thinks you are asking for the . Since MATLAB considers a variable to be a vector of length one.25π-th element of the vector sin.1 = 0 >> expm1(1.e-8) = 1.e-20) . Common Mathematical Functions the term within parentheses is very close to 1 and so subtracting by 1 causes a loss of many digits in the result.999999999999999e-21 Similarly. This can be avoided by entering x directly in x x2 x3 x4 log(1 + x) = − + − + ··· . if you enter >> sin(. z − 1 (z − 1)2 (z − 1)3 (z − 1)4 log z = − + − + ··· 1 2 3 4 so if z ≈ 1 then accuracy is lost in the calculation of z − 1.e-8) .25*pi) MATLAB will reply Warning: Subscript indices must be integer values. does it check if the word is a function. Similarly. >> exp(1.999999939225290e-09 >> expm1(1. only if it fails.e-20) = 9. The way to undo your mistake is by typing >> clear sin 12 . If you now type >> sin(3) MATLAB will reply ??? Index exceeds matrix dimensions.000000005000000e-08 >> exp(1. For example.5. because it recognizes that sin is a variable. Warning: There is one technical detail about functions that will trip you up occasionally: how does MAT- LAB determine whether a word you enter is a variable or a function? The answer is that MAT- LAB first checks if the word is a variable and.

acsc(x) arccsc x. y) The remainder of x/y. atan2(y. loge x. cot(x) cot x. floor(x) This is the largest integer acoth(x) arccoth x. is the same as mod(x. if x < 0 this returns −1. cos(x) cos x. degrees. exp(x) ex . ceil(x) The smallest integer which is secd(x) sec x where x is in degrees. ger which is ≤ x. asecd(x) arcsec x where the result is in log10(x) The common log of x. If it is not on your computer. 1.e.. Warning: be careful if x < 0.e. atanh(x) arctanh x. Complex Numbers Some Common Real Mathematical Functions abs(x) The absolute value of x. degrees. log1p(x) log(x + 1). ≥ x. 13 . tanh(x) tanh x. to find the roots of the quadratic polynomial x2 + 2x + 5 enter >> a = 1. cosd(x) cos x where x is in degrees. sign(x) If x > 0 this returns +1. asinh(x) arcsinh x.4*a*c ) ) / (2*a) The output is ˆ -1. csch(x) csch x.0000i and † This function is in the symbolic math toolbox. asech(x) arcsech x. x − n ∗ y where degrees. x) arctan y/x where the angle is in round(x) The integer which is closest to (−π. factorial(n) n! for n a non-negative acosd(x) arccos x where the result is in integer.6. degrees. b = 2.6. Complex Numbers MATLAB can work with complex numbers as easily as with real numbers. For example. sinh(x) sinh √ x. heaviside(x)† If x > 0 this returns 1. sqrt(x) x. sind(x) sin x where x is in degrees. asin(x) arcsin x.0000 + 2. n = floor(x/y). 1. tan(x) tan x. log10 x. sec(x) sec x. expm1(x) ex − 1. i.sqrt( b 2 . cotd(x) cot x where x is in degrees. tand(x) tan x where x is in degrees. acsch(x) arccsch x. the code is shown on page 104. rem(x. acot(x) arccot x. and degrees. if x = 0 this returns 0. sin(x) sin x. y > 0.. c = 5. +π]. coth(x) coth x. log(x) The natural log of x. >> x1 = ( -b + sqrt( b 2 . sech(x) sech x. mod(x. csc(x) csc x. x. cscd(x) csc x where x is in degrees. y) if atand(x) arctan x where the result is in x. which is ≤ x. acscd(x) arccsc x where the result is in if x < 0 this returns 0. and cosh(x) cosh x. If x < 0 this is the smallest acotd(x) arccot x where the result is in integer which is ≥ x. asind(x) arcsin x where the result is in That is. degrees. fix(x) If x ≥ 0 this is the largest inte- acosh(x) arccosh x. acos(x) arccos x. This atan(x) arctan x. if x = 0 this returns 1/2 .4*a*c ) ) / (2*a) ˆ >> x2 = ( -b . i. y) The modulus after division. asec(x) arcsec x.

† If a is a complex number. the imaginary part.m”. x. unless a semicolon ends it.0000i There are standard commands for obtaining the real part. 2 2i Some Common Complex Mathematical Functions abs(z) The absolute value of z = x + iy.0000 + 1. denoted by a∗ is obtained by changing the sign of i whenever it appears in the expression for a. >> x = 3 .e. 14 . then a∗ = 3√− 17i. and the complex conju- gate† of a complex number or variable. Script M-files -1.2. conj(z) z∗ = x − iy. real(z) The real part of z. Note that many of the common mathematical functions can take complex arguments. You can also create a new m-file or open an already existing one by >> edit <file name>. This type of file is called a script m-file: when MATLAB executes the command <file name> the contents of the file “ <file name>. i. and 3. if a = 3 + 17i. and the sequence can be executed whenever desired by typing >> <file name> The MATLAB statements themselves are not printed out. if we want to repeatedly execute a number of statements we have to put them all on one line and reexecute the whole line.m Warning: The name of the file includes the extension “. angle(z) The angle of z. Above. then a∗ = e−iπ/4 .m”.. -5. by atan2(y. Or click on File and then Open to open an already ex- isting one (if you want to modify it). if it asks.5i >> real(x) >> imag(x) >> conj(x) returns 3.0000i As another example. which is evaluated using the formula ez = ex+iy = ex (cos y + i sin y) . but you execute it in MATLAB by typing <file name>.. 1. if a = eiπ/4 .e.7. x). eiz + e−iz eiz − e−iz cos z = and sin z = . 1.0000 + 5.0000 .m.. We will not emphasize script m-files further.m” are executed just as if you had typed them into into the text window.e.7. but you will find many occasions where they are very helpful.e. Script M-files So far we have always entered MATLAB statements directly into the text window so that they are ex- ecuted immediately. √For example. This line can get very l o o o n n n g! The solution is to type the sequence of statements in a separate file named <file name>. This is calculated imag(z) The imaginary part of z. then a∗ = (2 − 3i) sin(1 − 3i)/(3 + 5 i). without the extension.0000i respectively. then its complex conjugate. to calculate eiπ/2 enter >> exp(1i*pi/2) and obtain 0. You can easily work on a script m-file by clicking on the menu item File and then on New to create a new m-file and finally. but the result of each statement is. Similarly. “<file name>. It is easy to edit this file to remove any errors. For example. click on Script. if a = (2 + 3i) sin(1 + 3i)/(3 − 5 i). i. i. i. However. MATLAB has calculated eiπ/2 .. y.

e. “ ”. Help! Warning: The file name can consist of (almost any number of) letters (lowercase and/or uppercase). i. The . 1. num- bers.8. and underscores.

Spaces are not allowed. Make sure your .rst character must be a letter.

. hold down the control key and type “c”).8).. For example. i. 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. it means you have already saved it.8.) To check this. Note: Typing 15 . MATLAB returns ??? Undefined function or variable 0 <file name> 0 . If MATLAB returns your m-file. Odds and Ends edit Create a new m-file or edit an already existing one. Lines can also be continued in the MATLAB workspace by using three periods. If it cannot find this particular function.. Continue an expression onto the next line. i. ˆ The on-line help facility in MATLAB is quite extensive. 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. i. you are safe. >> help <command> For example. A long expression can be continued to a new line by typing three periods followed by the “enter (or P20 “return”) key. simply type help followed by the name of the com- mand. it is often valuable to include comments to explain what you are doing. If you want help on a specific command.e. 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. which returns useful information about a MATLAB function. your file might not execute — MAT- LAB’s might! Or..le name is not the same as Warning: There is one point we cannot overemphasize. just type >> help format and you will see all the various ways that the output can be formatted. “%”. % Begin a comment 1.e. If it is. not one of yours. 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. but it is much more common to use continuation in an m-file.. Each line of comments must begin with the percent character. type Displays the actual MATLAB code for a command or function or m-file.. The answer is simply to type C (that is.e. . If your m-file is very long. one of MATLAB's commands or functions. if you forget the exact form of the format command. you can enter >> type <file name> before you save your m-file. In this case enter >> doc <file name> (which is discussed in the next section). If the file name doesn’t exist. Comments can appear alone on a line or they can follow a statement that you have entered.. 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 + . 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.

Warning: All of the thousands of MATLAB commands have to be checked. simply type the name of the variable on a line. while whos also returns the size and type of each variable. For example.8. Help! >> help ? gives you lots of information about arithmetical and relational and logical operators and special characters. “complex”.1. “complete”. To see what a variable contains. Sim- ply type who or whos to get a list of all your variables (but not their values). which are coded in C. This is always a good place to look if you are not sure how do do some- thing. The load command loads all the saved variables back into your MATLAB session. the entire function will be typed out for the former and appear in a new window in the latter. the string compl is contained in the words “complement”. It generally gives much more infor- mation than the help command. you might need to save one or more MATLAB variables: it might have taken you some time to generate these variables and you might have to quit your MATLAB session without finishing your work — or you just might be afraid that you will overwrite some of them by mistake.† (As we discuss in Section 4. called built-in function. when loaded back in using load the variables will be exactly the same as before. By the way. Use doc to learn how to save all the variables to a file of your own choice and how to save just some of the variables. and “incomplete” — and in the capitals of all these words. However. it is worth a try if you cannot remember the name of the command you want to use. There is a more general command that can help you determine which commands might be of use. Note: The string need not be a complete word. >> lookfor plot returns all the MATLAB commands that have something to do with plots. After working for a while. The save command saves the contents of all your vari- ables to the file “ matlab. since these com- mands are occasionally very helpful. the demonstrations available by running demo show many of the capabilities of MATLAB and include the actual code used. 16 . the load command can also be used to input our own data into MATLAB. 1. However. who simply returns the names of the variables you have defined.) † These variables are saved in binary format. Two commands that don’t quite fit in any category are save and load. If you want to find out more about a specific command.) This command may be useful — or it may not be. The contents can only be interpreted by the load command. and in a more easily understood format. (There are over one hundred. enter >> type <command> or >> edit <command> If the command is written in MATLAB’s programming language (as discussed in Section 8). For example.) MATLAB also has an entire reference manual on-line which can be accessed by entering >> doc or >> helpbrowser This hypertext documentation is displayed using your Web browser. It is case insensitive so capital letters need not be used. The command lookfor searches through the first line of all MATLAB help entries for a particular string. These commands can- not return anything useful on internal MATLAB commands. this is a good place to discuss them. you may well forget what variables you have defined in the workspace.mat”. Occasionally. so this command might run slowly. The contents of this file can be viewed by the user with an editor — but the contents will appear to be gibberish. “completion”.

This makes it much easier to understand MATLAB operations. and c and corresponding angles ∠ab.e. Consider a triangle with sides a.ans? √ 2. which are called vectors. i. doc <command> displays information about the command. i. c b to calculate ∠ac in degrees and show it in scientific notation. who Lists all the current variables.. Analytically. helpbrowser Accesses the main page of the on-line reference manual. Check whether this is also true numerically when using MATLAB by using a number of different values of θ. and ∠bc.e. whos Lists all the current variables in more detail than who. In this section we will generally refer to these sets of numbers specifically as vectors or matrices rather than use the more inclusive term “arrays”. Be Able To Do After reading this section you should be able to do the following exercises. help <command> displays information about the command. Arrays: Vector and Matrix Calculations In the previous section we discussed operations using single numbers. 1.2×1020 − 1220 i. 1. (b) Then show c to its full accuracy..7. to calculate c if a = 3. i. ∠ac. doc accesses the manual. This is also a good practice 17 . Until the advanced subsection at the end. and ∠ab = 79◦ . doc On-line help hypertext reference manual. How would you find out information about the fix command? 2. Notation: We will always write matrices using capital letters and vectors using lower case let- ters. cos 2θ = 2 cos2 θ − 1. b. (c) Use the law of sines. The solutions are given on page 163. (d) What MATLAB command should you have used first if you wanted to save these results to the file triangle. demo Runs demonstrations of many of the capabilities of MATLAB. Use MATLAB statements which make it as easy as possible to do this. (a) Use the law of cosines. load Loads back all of the variables which have been saved previously. b = 5. 3. scalars.e. MATLAB was originally developed specifically to work with vectors and matrices and that is still one of its primary uses.9. 4.. c2 = a2 + b2 − 2ab cos ∠ab . In this section we dis- cuss operations on sets of numbers called arrays. 2. we restrict our attention to one-dimensional arrays. lookfor <keyword> Searches all MATLAB commands for this keyword. C Abort the command which is currently executing (i. Arrays: Vector and Matrix Calculations Getting Help help On-line help.e. type <command> Displays the actual MATLAB code for this command. which are called matrices. and two-dimensional arrays. hold down the control ˆ key and type “c”).. save Saves all of your variables. help lists all the primary help topics. Calculate 3 1.7. sin ∠ab sin ∠ac = .

8 . Vectors are de- noted by boldface letters. 7 . (Any number of spaces can be put around commas or semicolons to improve the readability of the expression. If there is a distinction be- tween the real and complex case.1. 4. 7. having m rows and n columns) and Cm×n de- notes all complex m×n matrices.5.5. 4 . Rows can also be separated by beginning each on a separate line. xT . we have very specific notation for denoting vectors and matrices and the elements of each. Rm×n denotes all real m×n matrices (i. x = (xi ) means that the ith element of x is xi .. 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. 4 5 6 . 2. 2. we will use C rather than R unless there is a specific reason not to.1. 7 8 9] or >> A = [1. the element in the ith row and the j th column) is aij . In addition.9] However. the matrix A can also be entered by >> A = [1. The more complicated matrix √ 1 2+ 3 3 sin 1 C = e2 17/3 √ π+3 1/3 2 − 3 −7 cos π/7 18 . we will generally use them rather than commas to separate elements in a row. In addition. 5 .2. Notation: In this overview the word “vector” means a column vector so that Cm = Cm×1 .3 4. 3 . 4 5 6. Generating Matrices To generate the matrix 1 2 3 A = 4 5 6 7 8 9 in MATLAB type >> A = [1 2 3.) Notation: Since we prefer spaces.e. semicolons are required to separate rows. we will write a row vector as. 6 .8. Generating Matrices for you to use.9] or >> A = [ 1 .6.e. 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. 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. such as x.2. By the way MATLAB works with complex matrices as well as it does real matrices.. On the other hand. For example. 2 . Notation: Rm denotes all real column vectors with m elements and Cm denotes all complex column vec- tors with m elements. 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. either spaces or commas can be used to delineate the elements of each row of a matrix. where “ T ” denotes the transpose of a matrix or vector (that is. j)th element of A (i.6 7.) Notation: A = (aij ) means that the (i. 7 8 9] (where “ ” denotes one or more spaces) or >> A = [ 1 2 3 .3. the rows and columns are reversed. To remind you of this fact. Also. We collect all this notation here. we will first describe the real case and then follow with the complex case in parentheses. 9 ] In other words.8. for example.

e.) Warning: xT → x.. i. 5. 2. while AH is calculated by A 0 (i. pi+3. r = [ s2/s3 s2 s3 s2*s3 s2/s3 ] 0 or. is obtained by reversing the rows and columns of A and then taking the complex conjugates of all the elements. 6 . the vector r = 2/3 . 3 . a period followed by a single quote mark). where “ ∗ ” denotes the complex conjugate of a number. denoted by AT . is “ . 1/3. instead. just a single quote mark).. Note: In MATLAB AT is calculated by A. 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.) A vector can be entered in the same way as a matrix. The conjugate transpose of a matrix A ∈ Cm×n .. 1/3 2-sqrt(3) -7*cos(pi/7) ] or >> C = [ 1. if A = (aij ) then AT = (aji ). 4) element of AT . this requires many semicolons. just a single quote mark. exp(2). 3. There is one further simplification that is usually observed when entering a vector. take the transpose of a row vector by entering >> x = [1 2 3 4 5 6]. That is. 6)T 4 5 6 can be entered as >> x = [1. 2. 0 while xH → x 0 so that you can only calculate xT by x 0 if x is real.1. 0 ” (i.e. 4. Definition The transpose of a matrix A ∈ Cm×n . (We will discuss the colon operator shortly. 0 where the MATLAB command for the transpose. the vector 1 2 3 x = = (1. it is important to enter all the terms without spaces — unless everything is enclosed in parentheses. For example. 4. 5. x should be entered as >> x = [1:6] 0 since this requires much less typing. x is usually entered as >> x = [1 2 3 4 5 6] 0 Aside: In fact. 2. 2 .e. is a42 . Generating Matrices can be entered by typing >> C = [ 1 2+sqrt(3) 3*sin(1). 2+sqrt(3). as we will see later.. denoted by AH .e. exp(2) 17/3 pi+3. Thus. 0 (i. “ H ”. For example. if A = (aij ) then AH = (a∗ji ). That is. i. i. (For example. “ T ”. s3 = sqrt(3). a period followed by a single quote mark). 17/3. MATLAB tries to understand what you mean. by >> r = sqrt([2/3 2 3 6 2/3]) 0 19 . -7*cos(pi/7) ] Warning: When an element of a matrix consists of more than one term. but it does not always succeed. is obtained by reversing the rows and columns of A.e. 3. 2/3 can be entered by typing >> s2 = sqrt(2).e. A square matrix A is Hermitian if AH = A. The MATLAB command for the conjugate transpose.. which requires one less character than the command for the transpose. 6] However. 3*sin(1).. of a matrix is “ 0 ” (i. i = 2 and j = 4.e.) A square matrix A is symmetric if AT = A. 2-sqrt(3). For example. the (2.. >> x1 = [1 pi+3] is the same as >> x2 = [1 pi+ 3] and is the same as >> x3 = [1 (pi +3)] but is not the same as >> x4 = [1 pi +3] % not the same as the previous three statements (Try it!) In other words.

]... a different sequence of random numbers is generated.j) in MATLAB. not the seed. You work with individual elements of a matrix by using round parentheses. However. b) use >> R = a + (b .). n) To be precise.a)*rand(m.. . a matrix whose elements are all random numbers. just added. MATLAB also has a number of commands that can generate matrices. i. [. the default seed is set.3) = 10 Also. the element xi of the vector x is x(i) in MATLAB.. that is. Every time that a new MATLAB session is started. x(50) = x(50) + 1 or >> x = [1:50] 0 . i. by >> C = zeros(size(A)) where size(A) is a row vector consisting of the number of rows and columns of A. 47..n) To generate uniformly distributed random numbers in [a. Uniformly distributed random numbers in [0. n) or ones(size(D)). and so the same sequence of random numbers will be generated. 8) generates a 5×8 zero matrix. Suppose you want to create the matrix 1 2 3 B = 4 5 6 7 8 10 without having to enter all nine elements. to create the column vector x = (1. If desired. 48. these are pseudorandom numbers because they are calculated by a deterministic formula which begins with an initial “seed” — which is called the state . 49. For example. which takes the same arguments as above. i. Another useful matrix is a random matrix. (. 1) are generated by the rand function.e. you can generate a zero matrix C with the same size as an already existing matrix.. x(50) = 51 or >> x = [1:50] 0 . >> C = zeros(5) or >> C = zeros(5. >> C = zeros(5. the element aij of the matrix A is A(i. a different seed can be set at any time by entering >> rand( 0 state 0 . >> rng(<non-negative integer state number>) To general normally distributed random numbers with mean 0 and standard deviation 1 use >> R = randn(m. B(3. 51)T ∈ R50 enter >> x = [1:50] 0 . >> r = rand % or rand(1) >> R = rand(n) % or rand(m. The two most commonly used random numbers are uniformly distributed random numbers and normally distributed random numbers. you can generate a matrix with all ones by ones(n) or ones(m. 3. 2. the matrix with ones on the main diagonal and zeroes off of it. the simplest way is to type >> B = A. by using the command eye with the same arguments as above. . Finally. Generating Matrices We have now discussed how to enter matrices into MATLAB by using square parentheses. For example.. This command 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.e.e. i. every time that this command is executed during a session. such as A.1. . For example. Similarly. If A (see the beginning of this section) has already been gener- ated. Also. <non-negative integer state number>) or.e. 2. 5) generates a 5×5 zero matrix. x(length(x)) = x(length(x)) + 1 where length returns the number of elements in a vector. .. You can also generate the identity matrix. n) 20 .

to generate a 3×4 matrix whose first three columns are the columns of A and whose last column is (1. However. a reasonable approximation to it) occurs much more frequently in the physical world than the uniform distribution. let us continue with A (see the beginning of this section). 3) ] or by >> [ A . that is. This function can also be used to randomly generate any set of values (integer or real or even complex) by. 2. . rather than just generate random elements from a set. >> r = randi([k 1 k 2]) % or randi([k 1 k 2]. 3). 9)T type >> [A [1 5 9] 0 ] (The space following the A indicates that the next column is to follow. n) % or randi(k. . That is. The fact that A is a matrix in its own right is immaterial. including generating the normal distribution! There are two other probability distributions which are frequently needed. n) The normal distribution (or. Similarly. 2. Generating Matrices To obtain mean µ and standard deviation σ use >> R = mu + sig*randn(m. ones(2. m. All that is necessary is that the number of columns of A be the same as the number of columns of ones(2. . k] or >> R = randi(k. % the first nr primes prime numbers >> ir = randi(nr primes. n) which generates a matrix of integers. k2 ].) This matrix could also be generated by >> [ A . There is another “random” function which is useful if you want to reorder a sequence. for example. the uniform distribution has many uses. to put matrices together to make a larger matrix. 1) >> r = p(ir). 3) ] (The semicolon indicates that a row has been completed and so the next rows consist of all ones. ones(1. This is easily generated by >> [ A . n. at least. n) which generates one integer in the interval [k1 . Random matrices of integers are generated by >> r = randi(k) which generates one integer in the interval [1. The fact that the next entry is a column vector is immaterial. [1 1 1] ] or even by >> [ A . 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. the original matrices are submatrices of the final matrix. 5. [1 1 1] . n.1. This is called a random selection with replacement. >> nr primes = 10. MATLAB also makes it convenient to assemble matrices in “pieces”. For specificity. Suppose you want a 5×3 matrix whose first three rows are the rows of A and whose last two rows are all ones. ones(1. The command randperm(n) generates a random permutation of the integers 1. [1 1 1 . 3) .) 21 . . This is called a random selection without replacement. 1 1 1] ] Similarly. >> p = primes(nr primes).

<seed number>).9] 0 (although we can’t imagine why you would want to do it this way). Each time that this function is called during a session it returns different random numbers. 2. the vector x = (1. For example. AT . rand Generates a matrix whose elements are uniformly distributed random numbers in the interval (0. 5. 6. the diagonal elements are 1 and the off- diagonal elements are 0. we can generate num- bers in any arithmetic progression using the colon operator. . . A..2. The initial seed is changed by rand( 0 state 0 . a + 1. 9.2) returns the number of columns (the second element of A ). . length(x) The number of elements in a vector.e. typing >> [18:-3:2] generates the row vector (18. size(A) returns a two-vector of the number of rows and columns. 1). size(A) The size of a matrix.. n. Each time that this function is called during a session it returns different random numbers. 2. 15. The arguments are the same as for zeros. 2. randi uniformly distributed random integers. while typing >> [ pi : -.2. or [m. 12. size(A. zeros(m. The arguments are the same as for zeros.e. a + 2. The Colon Operator Elementary Matrices zeros(n) Generates an n×n matrix with all elements being 0. . ones Generates a matrix with all elements being 1. AH . i. The Colon Operator For real numbers a and b the MATLAB command >> [a:b] or. 2. numel(A) The total number of elements in a vector or matrix. Gaussian) distributed random numbers with mean 0 and standard deviation 1.1) returns the number of rows (the first element of A ) and size(A. more simply. . Thus.2*pi : 0 ] 22 .e.. 4. randperm(n) Generates a random permutation of the integers 1. i. 0 Transpose. . i. The arguments are the same as for zeros. 6)T should be entered into MATLAB as >> x = [1:6] 0 or even as >> x = [1:6. If c is also a real number the MAT- LAB command >> [a:c:b] or >> a:c:b generates a row vector where the difference between successive elements is c.n] = size(A) returns m and n as separate arguments.e. . Thus. Also. . eye Generates the identity matrix. 3. >> a:b generates the row vector (a. 3). zeros(size(A)) Generates a zero matrix with the same size as A. randn Generates a matrix whose elements are normally (i.. A0 Conjugate transpose. a + k) where the integer k satisfies a + k ≤ b and a + (k + 1) > b. n) Generates an m×n matrix. The arguments are the same as for zeros. rng Generates a seed for the random number generator.

You might be changing the size of E and not want to have to remember how large it is.3:4) = 2*F(:. It also ends a block of code begun with a if. For example. For example.98. However.001 ) generates successive values of i by adding 0.† We will discuss the command linspace which avoids this difficulty in Sec- tion 4. 0. and fifth columns of E. the second column of F is F(:.4*F(:. Warning: There is a slight danger if c is not an integer. 0.6π. 23 . The MATLAB package was written specifically to minimize such a possibility. This can be easily done by >> F = E( [1:2:end] . as we did above.02 : .2) = 2*F(:.2) and the second row is F(2. fourth.98.001 : . . thus.:). 7:12 .3:4) There is a last-additional shortcut you can use. . As an oversimplified example. It is possible that when i should have the value 0. third. 13:18 . or switch (as we will see later). 0. 2:5 ) There is an additional shortcut you can use: in a matrix a colon by itself represents an entire row or column. while. . An easy “fix” to avoid this possibility is to calculate x by >> x = [20:980] 0 /1000 2. Manipulating Matrices For specificity in this subsection we will mainly work with the 5×6 matrix 1 2 3 4 5 6 7 8 9 10 11 12 E = 13 14 15 16 17 18 . because of round-off errors in storing floating-point numbers.979.979.98 will be false and the loop will not be evaluated when i should be 0. [2 3 4 5] ) extracts the elements in the first. Note: The keyword end has a number of meanings.02. there is a possibility that the last element in x will be 0. entering >> x = [.98] 0 should generate the column vector (0.98)T .021. . For example.2) . the condition i <= 0. for. 19:24 . .3. 2 3 4 5 F = 14 15 16 17 .98. 2. due to round-off errors the value will be slightly larger.4) And suppose you now want to double all the elements in the last two columns of F.4π. .022. 0). [2:end] ) The keyword end designates the last element of the dimension: 5 for the rows of E and 6 for the columns.001 to the preceding value. but it still remains.8π.2π. third. Simply type >> F(:.02. You can use the colon notation to extract submatrices from E. 26 27 28 29 You can generate this submatrix more easily by typing >> F = E( 1:2:5 . MATLAB will not complain. >> F = E( [1 3 5] . it will simply return “ []” which is an empty matrix. . Suppose you want the matrix F to consist of the odd rows of E and the second to the last column. i <= 0. i = i + . . the statement for ( i = 0. 19 20 21 22 23 24 25 26 27 28 29 30 which can be generated by >> E = [ 1:6 .3. it can also terminate a primary function or a † This possiblity is much more real in the programming language C.1. 25:30 ] Note: Spaces will frequently be used in MATLAB commands in this subsection for readability. Occasionally your fingers will go crazy and you will type something like >> [10:1] (rather than [1:10] ). Manipulating Matrices generates the row vector (π. 0. and fifth rows and the second. Finally. To replace the second column of F by two times the present second column minus four times the fourth column enter >> F(:.

1) (so d1 is the column vector (2. 1) generates a 6×6 matrix whose first diagonal elements (i. 1. 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. Entering >> f = E(:) generates a column vector consisting of the columns of E (i. 6 5 4 3 2 1 12 11 10 9 8 7 G = 18 17 16 15 14 13 . it generates a symmetric matrix. Note: On the right side of an equation. one above the main diagonal by typing >> d1 = diag(E.:) = G([3 5].:) = G(5.) Finally. one above the main diagonal) are the elements of d1. A different command is needed to work on the diagonals of a matrix. reverses the values in these two variables. 23. 20.. entering >> F1 = diag(d1. Returning to “ :”.e. and more transparent. 2. 29)T ). y). The MATLAB function diag transforms a matrix (i.e. On the other hand. and whose other elements are zero. E(:) is a column vector with the elements being the columns of E in order. and whose off-diagonal elements are zero. 8. entering >> G = E( : .:) which is much simpler. you extract the main diagonal of E by typing >> d = diag(E) (so d is the column vector (1. 23.. Similarly. For example. entering E(:.3. the first five elements of f are the first column of E. For example. 30.:) prints out exactly the same matrix as entering E (as does E(1:end. 0 2 0 0 0 0 0 0 9 0 0 0 0 0 0 16 0 0 F1 = .:) >> G(3. 22. x] = deal(x. -2) (so d2 is the column vector (13.. 0 0 0 0 23 0 0 0 0 0 0 30 0 0 0 0 0 0 24 .:) >> G(5. we will not discuss this reshaping further because the reshape command described below is easier to understand. 27)T ). 6:-1:1 ) generates a matrix with the same size as E but with the columns reversed.e. The command >> F = diag(d) generates a 5×5 matrix whose main diagonal elements are the elements of d.:) = temp Note: There is a more general function which can reverse two variables: scalars or vector or matrices. The colon operator works on rows and/or columns of a matrix.e. The con- verse also holds: when diag is applied to a vector. i. 22. 16. and it must terminate a nested function (as we will also see later). a non-vector) into a column vector. that is. For example. 24 23 22 21 20 19 30 29 28 27 26 25 It is also very easy to switch rows in a matrix. >> [y. 9. Manipulating Matrices subfunction. to switch the third and fifth rows of G. enter the single line >> G([5 3]. However. 15. the next five elements of f are the second column of E. 16. 29. X] = deal(X.e. This is not a very useful way of entering E. % or [Y. Y). 15. i. i. On the left side of an equation. 8. but it shows how the colon operator can work.e..1:end) ). than the three lines >> temp = G(3. E(:) reshapes a matrix. and two below the main diagonal by typing >> d2 = diag(E. etc.. there is one more use of a colon.). 30)T ).. 2. 9.

only the row or the column elements need be entered (i. 0 2 3 4 5 6 0 0 9 10 11 12 G2 = 0 0 0 16 17 18 .. reverses the columns of the matrix.. 13. [7 4 3 1]) If the Topelitz matrix is symmetric. 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. As an example of the relationship between these three commands. the other elements of G1 are zero. Instead. >> 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. i. This command can also be applied to any of the diagonals of a matrix.. 1) + tril(F) Note: Numerically the first command might not generate exactly the same matrix as the following three because of round-off errors. only one argument is required). 20. 25 .triu(F.e.. flipud(A) flips the matrix up and down. 1). -2) generates a 5×5 matrix whose −2nd diagonal elements (i. 1). i. -1) >> triu(F) + tril(F. -1) >> triu(F. i. 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].e. 1) + diag(diag(F)) + tril(F. 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. triu and tril cannot appear on the left-hand side of an equation. 2. 0 0 0 0 23 24 0 0 0 0 0 30 The similar command tril extracts the lower triangular part of a matrix. to zero out all the diagonals above the main diagonal of F enter >> F = F . 2) + diag(diag(F. You can also extract the upper triangular or the lower triangular part of a matrix.e. two below the main diagonal) are the ele- ments of d2.diag(diag(F)) >> triu(F. 27..e.tril(triu(F. Manipulating Matrices Finally.. reverses the rows of the matrix.e. 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.. >> G2 = triu(E. typing >> F2 = diag(d2. For example. consider the square random matrix F generated by >> F = rand(6) All the following MATLAB commands calculate F anew: >> triu(F) + tril(F) .e.e.3. i. i. and whose other elements are zero. It is important to note that diag . For example. 0 0 0 0 0 0 0 0 0 0 F2 = 13 0 0 0 0 . 1) and to zero out just the first diagonal above the main diagonal enter >> F = F .

n) (but it is much faster if m and n are large since no multiplication is involved). Manipulating Matrices rot90(A) rot90 rotates the matrix 90◦ . The command >> B = repmat(A. . 2:2:6 ) = [] The result is 6 4 2 12 10 8 G = 18 16 14 . . 4)T . This even works if A is a scalar. then B ∈ Rmp×nq . 1. occasionally. For example. the first m elements of this column vector go in the first col- umn of K. 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.) If A is a p by q matrix. suppose that the column vectors { x1 .k) rotates the matrix k×90◦ .3. n]. m) is sufficient. we can enter 26 . This can be easily done by >> Y = X + repmat(a. the second m elements go in the second column. . unfortunately. MATLAB has a command which is useful in changing the shape of a matrix while keeping the same numerical values. requires that the new matrix A = repmat(a. 2. m. etc. 5) 0 Occasionally. . A column vector is generated from H. (If n = m then repmat(A. and the elements of K are taken columnwise from this vector. n) be created. For example. That is. 24 22 20 30 28 26 Also. m. there is a need to replicate or tile a matrix to form a larger matrix. entering >> x = [1 2 3 4] 0 >> x(2) = [] results in x = (1. n) reshapes the matrix H ∈ Cp×q into K ∈ Cm×n where m and n must satisfy mn = pq (or an error mes- sage will be generated). you can delete the even columns of G by >> G( : . x2 . n). 1. there is a need to delete elements of a vector or rows or columns of a matrix. n) generates a matrix B which contains m rows and n columns of copies of A. as in H(:). However. and rot90(A. 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. We would prefer to simply enter >> Y = X + a (WRONG). 3. which. 6. For example. the matrix E which has been used throughout this subsection can be easily (and quickly) generated by >> E = reshape([1:30]. This is easily done by using the null matrix []. As another example. The statement >> K = reshape(H. in which case this is the same as >> B = A*ones(m.

2. 27 . This command can actually be applied to multi- dimensional matrixes. which. A. is much faster than using repmat. Manipulating Matrices >> Y = bsxfun(@plus. X. The simplest operation is to let the function handle be one of the following: Built-in Functions for bsxfun @plus Plus @hypot Hypotenuse @minus Minus @eq Equal @times Array multiply @ne Not equal @rdivide Array right division @lt Less than @ldivide Array left division @le Less than or equal to @power Array power @gt Greater than @max Binary maximum @ge Greater than or equal to @min Binary minimum @and Logical AND @rem Remainder @or Logical OR @mod Modulus @xor Logical exclusive OR @atan2 Arctangent Of course. <fun> is a function handle which operates on the matrix A ∈ Rm×n and the column vector b ∈ Rm or the row vec- tor b ∈ R1×n .3. incidentally. it then outputs a column vector of the same size as the input. b). but we will only describe it for bsxfun(<function handle>. it is possible to write your own function which inputs either two column vectors of the same size or one column vector and one scalar. a).

) bsxfun(<fnc>. then k = 1. (If n = m the third argument is not needed. . A(i. then k = 0... jr]. A.j) ai. If k is not given. j)th element of A + B is aij + bij .. n) Generates an m×n matrix whose elements are taken columnwise from A.?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 . this is a column vector containing the columns of A one after the other. rot90(A) Rotates a matrix k×90◦ . then k = 0.5*pi ] 0 28 . the (i. . diag(d) A square matrix with the k th diagonal being the vector d. B ∈ Cm×n then the MATLAB operation >> A . . If k is not given. 2. m. k) repmat(A. triu(A) A matrix which is the same size as A and consists of the elements on and o triu(A. If k is not o diag(d. c and r are the values on the first diagonal and the first row respectively. diag(A) A column vector of the k th diagonal of the matrix (i. the matrix q = (0.. Note: The number of elements in A must be mn. Simple Arithmetical Operations Manipulating Matrices A(i. This is also useful for deleting elements of a vector and rows or columns of a matrix. Matrix Multiplication by a scalar: If A ∈ Cm×n then for any scalar c the MATLAB operation >> c*A means cA = c(aij ) = (caij ). k) given. If k o diag(A.2π.3π. m.1π. flipud(A) Flips a matrix up and down. k) is not given.4.B means A − B = (aij ) − (bij ) = (aij − bij ).r) Generates a Toeplitz matrix where the elements along each diagonal are constant. non-vector) A. k) above the k th diagonal of A. Matrix Subtraction: If A. A(:.j) the j th column of A. then k = 0. n) Generates a matrix with m rows and n columns of copies of A.4π. k) the k th diagonalof A. toeplitz(c.4. A(:) On the right-hand side of an equation. [] The null matrix. fliplr(A) Flips a matrix left to right.1*pi : . ir] and ?2 can be j or j1:j2 or j1:j3:j2 or : or [j1 j2 . . A(:.e. A(?1. B ∈ Cm×n then the MATLAB operation >> A + B means A + B = (aij ) + (bij ) = (aij + bij ).. o rot90(A. Simple Arithmetical Operations Matrix Addition: If A.5π)T can be gener- ated by >> q = [ 0 : . For example. 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.j . If k is not given. . tril(A) The same as the command triu except it uses the elements on and below o tril(A.:) A itself. then k = 0. 2. That is.:) the ith row of A.

Matrix Exponentiation: If A ∈ Cn×n and p is a positive integer. 3 4]. This is much faster computationally than calculating the solution of x = A−1 b by >> x = inv(A)*b Similarly. then the MATLAB operation >> A.5 ] 0 *pi or >> q = [0:5] 0 *. Instead. Matrix Division: The expression A B makes no sense in linear algebra: if B is a square non-singular matrix it might mean B−1 A or it might mean AB−1 . 3y3 . the (i. For example. 0 /A and to solve XA = B by B/A (This is the same as solving AT XT = BT . then the MATLAB operation >> A p ˆ means Ap = AA · · · A} . Simple Arithmetical Operations but more easily by >> q = [ 0 : .) Note: For two values of p there are equivalent MATLAB commands: A1/2 can also be calculated by sqrtm(A) and A−1 can also be calculated by inv(A).*B is aij bij . . Elementwise Division: 29 . the (i.4. B ∈ Cm×n . nyn )T . all of its elements are less than 10 · eps in magnitude. use the operation >> A\b to calculate the solution of the linear system Ax = b (where A must be a square non-singular ma- trix) by Gaussian elimination. 2. . j)th element of AB is ai1 b1j + ai2 b2j + · · · + ai` b`j . It is also possible to solve xT A = bT for xT by b. j)th element of A. For example. . 0 .* [1:n] (where the spaces are for readability). That is. That is. Note that this is not a matrix oper- ation. Recall that if y ∈ Cn you will have to enter >> z = y.1*pi Matrix Multiplication: If A ∈ Cm×` and B ∈ C`×n then the MATLAB operation >> A*B P ` means AB = (aij )(bij ) = k=1 a ik b kj .1 : . >> A = [1 2.* [1:n] because you do not want to take the complex conjugate of the complex elements of y. suppose y ∈ Rn has been defined previ- ously and you want to generate the vector z = (1y1 .*B means (aij bij ). 2y2 . A\B solves AX = B by repeatedly solving Ax = b where b is each column of B in turn and x is the corre- sponding column of X. You merely type >> z = [1:n] 0 . (Analytically.* y or >> z = y 0 .A ˆ returns a non-zero matrix — however. | {z p times Matrix Exponentiation is also defined when p is not an integer. B = A (1/2) ˆ calculates a complex matrix B whose square is A. B2 = A. .) Elementwise Multiplication: If A. but it is sometimes a useful operation. but numerically >> B 2 .

Elementwise Left Division: If A. MATLAB checks that the matrices have the correct size. p ˆ means (apij ) and >> p. the number of fl oating-pointoperations. >> y = 2*sin(3*x + 4) . i. It is calcu- lated by >> a 0 *b (If a. b are complex the outer product is abH and is calculated by a*b 0 . then the MATLAB operation >> B. i. Simple Arithmetical Operations If A. Note: There is one exception to this rule. B ˆ b means aijij . b ∈ Cn the inner product is aH b and is calculated by a 0 *b. i. 1) In some courses that use vectors. and >> A*B will return an error message if the number of columns of A is not the same as the number of rows of B. b ∈ Rn by aT b. Unfortunately. B ∈ Cm×n .e. the dot product of the real vectors ~a and ~b is defined by n ~a q~b = X ai bi . >> A + c is evaluated as >> A + c*ones(size(A)) This is not a legitimate expression in linear algebra. i=1 In linear algebra this is called the inner product and is defined for vectors a. 3] by 101 data points using >> x = [2:./B Elementwise Exponentiation: If A ∈ Cm×n .01:3] 0 . such as statics courses.e. aH b ∈ C ). B ∈ Cm×n ... performed during the MATLAB session. abH ∈ Cn×n ). For example. you can represent the function y = 2 sin(3x + 4) − 5 for x ∈ [2. aT b ∈ R (if complex. then >> A. B ∈ Cm×n . 1)) .5*ones(101. In the distant past. if A. >> A + B will return an error message if A and B have different sizes. abT ∈ Rn×n (if complex.) It is important to keep these two products separate: the inner product is a scalar. MATLAB kept track of the number of flops. then the MATLAB operation >> A.5 This is much more intelligible than calculating y using >> y = 2*sin(3*x + 4*ones(101. the scalar is promoted to the matrix cJ where J has the same size as A and all its elements are 1. while the outer product is an n×n matrix..) The outer product of these two vec- tors is defined to be abT and is calculated by >> a*b 0 (If a. In linear algebra we often work with “large” matrices and are interested in the amount of “work” re- quired to perform some operation.\A means the same as A. For example./B means (aij /bij ). 2. When a scalar is added to a matrix.4. Also. as in A + c. A ˆ means (paij ).e. but it is a very useful expression in MATLAB. Where needed in these arithmetic operations. then A. That is. this dis- 30 .

Central Processing Unit. cputime Approximately the amount of CPU time (in seconds) used during this session. the order in which it evaluates an expression. we can calculate the amount of CPU time† required to execute a command by using cputime. that is. the elapsed time might be much greater than the CPU time. On the other hand. Operator Precedence It is important to list the precedence for MATLAB operators. >> tic.5. toc Returns the elapsed time between these two commands. tic followed by toc is exactly the same as if you had used a stopwatch to determine the time. Operators with the same precedence are evaluated from left to right in an expression. p Elementwise exponentiation. 2. <sequence of commands>.\A is singular matrix. cputime . A-B Matrix subtraction. time = cputime.\A Elementwise left division. 31 .time Warning: Remember that you have to subtract the CPU time used before the operation from the CPU time used after the operation. does MATLAB do (A*C)\b or A*(C\b)? The former is C−1 A−1 b while the latter is AC−1 b — and these are completely different. tic. A\B The solution to AX = B by Gaussian elimination. Since a timesharing computer can be running many dif- ferent processes at the same time. toc returns the time in seconds for this sequence of commands to be performed. elimination when A is a square non. is the “guts” of the computer. A A n Matrix exponentiation. b/A The solution to xA = b where x and b are row vectors. Arithmetical Matrix Operations A+B Matrix addition.. 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. For example. This time is frequently difficult to calculate. B. B A\b ˆ The solution to Ax = b by Gaussian ˆ A.5. Operator Precedence appeared in version 6. The following ta- ble shows the precedence of all MATLAB operators. You can also calculate the wall clock time required for some sequence of commands by using tic and toc . in which order does MATLAB do the calculations? For example. the elapsed time might be much less. That is. A*B Matrix multiplication. ˆ A./B Elementwise division. ˆ p. and is seldom more accurate than to 1/ 100 -th of a second. that is./B. on a multiprocessor computer. B/A The solution to XA = B by Gaussian elimination. Note: This is very different from using cputime.e. inv(rand(n)). if an expression uses two or more MATLAB operators. 2. † The CPU. >> n = input( 0 n = 0 ). i. Instead. A. B. the hardware that executes the instructions and operates on the data. Here is a simple example to determine the CPU time required to invert a matrix. A. The precedence is from highest to lowest.*B Elementwise multiplication. This command returns the CPU time in seconds that have been used since you began your MATLAB session. exactly the same as A.

0000 0..\ . x = 5 + 1 and x = 10 − 13. . Entering >> format short e >> ans † On the other hand. A*C\b = (A*C)\b because “ *” and “ \” have the same precedence and so the operations are evaluated from left to right. [unary minus] . 0 .) To calculate the eigenvalues of the Hilbert matrix of or- der 5.6. (We discuss eigenvalues in Section 7. Be Careful! Operator Precedence (highest to lowest) operators with the same precedence are separated by funny commas 1 ( .2085 1.. ) 2 . > .6. 32 . .2) enter >> format short >> eig(hilb(5)) MATLAB displays the eigenvalues as the column vector ans = 0.e. However. i. 0 . / ./ . if it was zero MATLAB would display 0 and not 0. 8 & ˜= 9 | 10 && 11 || The unary plus and minus are the plus and minus signs in x = +1 and x = −1.0003 0. >= . for example. 3 ˆ ˆ + [unary plus] .† Also.. The plus and mi- nus signs for addition and subtraction are. ∗ . Be Careful! Be very careful: occasionally you might misinterpret how MATLAB displays the elements of a vector or matrix.. == . 1:n+1 is 1:(n+1) because “ +” has higher precedence than “ :”... <= .5671 You might think the the first element of this vector is 0. \ ˜ 5 + [addition] ... Thus.. − [subtraction] 6 : 7 < .0114 0.∗ .... in the statistical computer languages R and S (which are somewhat similar to MATLAB)... 2. 4 .0000.. the MATLAB command eig calculates the eigenvalues of a square matrix.. 1/ 1/ 1/ 1/ 1/ 4 5 6 7 8 1/ 1/ 1/ 1/ 1/ 5 6 7 8 9 (we discuss this matrix in detail in Section 5. 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 . . For example. “ :” has higher precedence than “ +” and so 1:n+1 is (1:n)+1 ≡ 2:(n+1).. 2. ..

1168 -0.4421 It is very easy to miss the term “ 1.1407e-02 2. entering >> format short e >> ans displays ans = 1.1168e+00 -8.0e+10 * 1. but is simply too small to appear in this format. It only appears to be nonzero when calcu- lated by MATLAB because computers cannot add.0e+10 *” because it stands apart from the elements of the matrix. multiply. entering 33 . /2 1/3 We write H100 as 1.8262 0.4421 while in MATLAB entering >> format short >> H = hilb(2) >> H 100 displays ˆ ans = 1.0463e-16 Since the last eigenvalue is close to eps.0853e-01 1.8262 H100 ≈ 1010 .5671e+00 which makes it clear that the smallest eigenvalue is far from zero. However.8262 0. On the other hand. you can safely assume that this eigenvalue is zero analytically. 7 8 9] >> eig(A) MATLAB displays ans = 16. Be Careful! displays ans = 3.0000 It might appear from our previous discussion that the last eigenvalue is not zero.6117e+01 -1. 2. 0.5437 0.8262 0. 4 5 6.2879e-06 3. Similarly.5437 0.6.0590e-04 1.1168 -1. consider the Hilbert matrix of order two 1 1/2 H= 1 . if you enter >> format short >> A = [1 2 3. subtract. but all the numbers in the matrix A are of “reasonable size”. or divide correctly! As another example of how you might misinterpret the display of a matrix.

0e-15 * 0. 2. it should be zero. since (H1/2 ) = H. However. it is easy to miss the term “ 1.8. MATLAB displays ans = 1.H ˆ ˆ 2 should result in the zero matrix. Data Manipulation Commands >> format short >> H = hilb(2) >> ( H (1/2) ) 2 .e-15 *” and not realize that this matrix is very small — in fact.2220 0 0 0 where. again. Be careful: MATLAB has .

i. if you want D = aij type >> C = sqrt(A) or >> C = A. this new interpretation of mathematical functions makes it easy in MATLAB to graph functions without having to use the MATLAB programming language. (1/2) ˆ All the common mathematical functions in the table entitled “Some Common Real Mathematical Func- tions” in Section 1. Data Manipulation Commands MATLAB has a number of “simple” commands which are used quite frequently. To calculate the maximum value of the vector x. []. even if you have sufficient memory. For example. For example. If you have large matrices which are no longer needed. The whos com- mand will tell you how much memory you are using and show you the size of all your variables. we have grouped them around this common theme. i] = max(x) If the elements of the vector are all real. type >> m = max(x) If you also want to know the element of the vector which contains this maximum value. or remove them entirely by using clear. i... As we will see in the section on graphics.. MATLAB may slow to a crawl and become unusable.) Here we are interested in how MATLAB applies common mathematical functions to matrices and vec- tors. However. you might want to take the sine of every element of the matrix A = (aij ) ∈ Cm×n .e.nite memory. Common Mathematical Functions In linear algebra mathematical functions cannot usually be applied to matrices. you can reduce their sizes by equating them to the null matrix. 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.8. Frequently it is much larger than the amount of physical memory on your computer. type >> [m. Warning: Recall that the clear command is very dangerous because clear A deletes the variable A but clear (without anything following) deletes all variables! 2. the result of this command is the element which has the maxi- mum value. Since many of them are quite useful in analyzing data. if any of the elements of x are complex (i. B = (sin aij ).7. eA and sin A have no meaning unless A is a square matrix.e. But. if you want C = (eaij ). This is easily done in MATLAB by >> B = sin(A) Similarly. (We will discuss their mathematical definitions in Section 15. non-real). this command has no math- 34 .e.5 can be used in this way. enter >> C = exp(A) p Also. 2.

then max(x) is not the same as max(abs(x)). 2. 20). That is. type >> sum(x) sum behaves similarly to max when applied to a matrix. then it determines the maximum value of a vector or the maximum value in each column of a matrix. if x = (−2. >> max(A) returns a row vector of the maximum element in each of the columns of A if all the elements of A are real. 1)T then max(x) returns 1 as expected.. 1/13 + 1/14 + 1/15 + 1/16 + 1/17 + 1/18 + 1/19 + 1/20 is entered much more easily as >> sum(ones(1. >> A = max(A. of these elements is calculated by >> mean(x) where mean(x) = sum(x)/length(x). This is because the element which has the largest absolute value is −2. the command min acts similarly to max except that it finds the minimum value (or element with the minimum absolute value) of the elements of a vector or the columns of a matrix. or one or both is a scalar. std calculates the standard deviation of the elements of a vector. type >> max(max(abs(A))) or >> max(abs(A(:))) There is also another use for max. type >> max(max(A)) or >> max(A(:)) and to find the maximum absolute value of an entire real or complex matrix. i)T then max(x) returns −2. MATLAB can also sort the elements of the vector x in increasing order by 35 . if x = (−2. Thus. The standard deviation is a measure of how much a set of numbers “vary” and is defined as n 1/2 1X 2 std(x) = xi − h x i n i=1 where h x i is the mean of the elements. For example. >> 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9 + 1/10 + 1/11 + 1/12 + .. Note: If max has one argument. this command can also be applied to matrices.8. if x is a non-real vector. B) returns a matrix which is the same size as A and B (or the size of the larger if one is a scalar) and which contains the larger of the values in each element. Warning: Make sure you understand the description of max if you every apply it to non-real vectors./[1:20]) The mean. Data Manipulation Commands ematical meaning. This command is sometimes useful in adding a deterministic series. If any of the elements of A are non-real. If A and B are matrices which either have the same size. 0) replaces all negative elements of A with zeroes./[1:20]) or even as >> sum(1. this command returns the element in each column which has the maximum absolute value of all the elements in that column. If it has two arguments. it determines the maximum value of each ele- ment of the two matrices. For example. To calculate the sum of the elements of the vector x. MATLAB defines this command to determine the element of the vector which has the maximum absolute value of the elements of x. For example. Since the columns of the matrix A can be considered to be vectors in their own right. then >> max(A. it returns the row vector of the sums of each column of the matrix. However. To find the maximum value of an entire real matrix. or average. Not surprisingly. Thus.

namely cumprod. in which case they act on each column of the matrix separately. if s ∈ Rn−1 has been generated by s = diff(x). (Note that this is not length(x) which returns the number of elements in x. • a numerical approximation to the derivative of y = f (x) can be calculated by diff(y). the norm of a vector is a more general concept than simply the Euclidean length. which is x21 + x22 + · · · x2n . x2 . These are both discussed in Section 4. the one with the smaller absolute angle in polar coordinates is used. which is often called the Euclidean length. such as the average and standard deviation. For example.) 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).1.) The MATLAB function which is almost the inverse of diff is cumsum. (If two elements have the same absolute value. xn ) by >> [1. Data Manipulation Commands >> sort(x) If the vector is non-real. there is always an optional argument (usually the second) which can change the command so that it acts on each row of the matrix. . 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 command. • similarly. .n))] and (1!. then if any element of diff(s) is 0./diff(x). 3!. For example. . which are discussed in Section 8.) This length. x. To actually “see” what the data looks like. cumprod(x*ones(1. Two particu- larly useful types of plots are histograms (which show the distribution of the data) and plots of data which include error bars. if x ∈ Rn then the command >> s = diff(x) generates the vector s ∈ Rn−1 which is defined by si = xi+1 − xi . . are used to determine if any the elements of a vector satisfy some property and/or if all the elements satisfy it. However.. then >> c = cumsum(s) Pi generates the vector c ∈ Rn−1 where ci = j=1 sj . if all the elements of diff(x) are positive. . then all the elements of s are monotonically increasing. the elements are sorted in increasing absolute value. The commands we have just discussed. n. It calculates the cumula- tive sum of the elements of a vector or matrix.) The MATLAB function diff calculates the difference between successive elements of a vector. give a coarse measure of the distribution of the data. There are also a number of MATLAB commands which are particularly designed to plot data. . There are a number of uses for this command.8. 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. • if s has been sorted. . n!) by >> cumprod(1:n) Note: All of these commands can be applied to matrices. 36 . an element of s has been repeated — and we can even determine the number of times it has been repeated.2. Thus can be used to generate (1. 2. . (The functions any and all . sometimes you want to know the length of a vector x. 2!. For example. pAlthough it does not quite fit here. it has to be plotted. i.e.

The 3-D array Mall can contain all these im- ages: Mall(i. vectors) and 2-D arrays (i. or a row vector containing the o std(A) standard deviation of the elements in each column in a matrix. norm(x) The Euclidean length of a vector. (product. Now suppose the company has five sales regions so we split the amount of each product into these regions. the data naturally fits in a 3-D array. Many MATLAB functions can be used in n-D. the data nat- urally fits in a 2-D array. amount). or average. suppose a company produces three products and we know the amount of each product produced each quarter. suppose that each product comes in four colors. i.k) = M If you want to multiply M by another matrix A.e. (product. max(A) A row vector containing the maximum element in each column of a matrix. or a row vector containing the sums of the o sum(A) elements in each column in a matrix. The cat func- 37 . diff(x) The difference between successive elements of a vector. (product. Note: the norm of a matrix is not the Euclidean length of each column in the matrix. n-D arrays). Finally. 2.:. mean(x) The mean.. amount). you can use M*A or Mall(:. min(x) The sum of the elements of a vector.j denoting the value of the pixel positioned at (xi .j. [m.9.e. i] = max(x) also returns the element which contains the maximum value in i.1)+Mall(:. In MATLAB you can also use multidimensional arrays (i. or between succes- o cumprod(A) sive elements in each column of a matrix. For example. such as ones. norm(A) The matrix norm of A. i.k) denotes the value of the pixel positioned at (xi . sum. yj ).9.e. cumprod(x) The cumulative product between successive elements of a vector. or between successive ele- o diff(A) ments in each column of a matrix.e. i] = max(A) also returns the element in each column which contains the max- imum value in i. sum(x) The sum of the elements of a vector.k)*A. amount). rand. Suppose we record a grey scale digital image of an experiment every minute for an hour. of the elements of a vector. cumsum(x) The cumulative sum between successive elements of a vector. The entire k th image is Mall(:. there are many operations and functions which can be applied to them. For another example.. Advanced Topic: Multidimensional Arrays We have already discussed 1-D arrays (i. or between successive o cumsum(A) elements in each column of a matrix. 2. matrices).. Since these are two of the most fundamental objects in linear algebra.:. prod(x) The product of the elements of a vector. the data naturally fits in a 4-D array.k) and it is filled with the k th image M by >> Mall(:. or in each column of a real o sort(A) matrix. sort(x) Sorts the elements in increasing order of a real vector. A common use for multidimensional arrays is simply to hold data. and size. color. Each image is stored as a matrix M with mi. region.B) Returns an array which is the same size as A and B (they must be the size or one can be a scalar) and which contains the larger value in each element of A or B. region. or a row vector containing the product of o prod(A) the elements in each column in a matrix. i.:. Advanced Topic: Multidimensional Arrays Data Manipulation Commands max(x) The maximum element of a real vector. a 3-D array might be the time evolution of 2-D data. if you want to average the first two images you can use .e. max(A. or a row vector containing the sum of the o min(A) elements in each column in a matrix..e.5*(Mall(:.:.:.2)).. yj ) in the k th image. or a row vector containing the o mean(A) mean of the elements in each column in a matrix.. std(x) The standard deviation of the elements of a vector. [m.

A.e. i. D].10. A) That is. (ii) since each row is in arithmetic progression. B. A) >> ABCD = ipermute( BCDA. >> ABCD(:. Another useful command is squeeze which squeezes out dimensions which only have one element.:.10. “ size(E) = 2 1 4” so that E is a three- dimensional array. C. B. Be Able To Do tion is particularly useful in generating higher-dimensional arrays. C. D) then the four matrices are concatenated along the j th dimension of ABCD. C. . n.e. B. squeezes out) dimensions which only have one element. That is. B. For example. squeeze Removes (i. C. D) >> BCDA = permute(ABCD. C. D. Consider the matrix 1 2 3 4 5 6 7 8 A= . [2 3 4 1] ) Multidimensional Array Functions cat Concatenates arrays. (iii) since each column is in arithmetic progression. C. ipermute The inverse of permute. >> ABCD(:. ipermute is the inverse of permute so. A. A. D) is the same as [A. permute Reorders the dimensions of a multidimensional array. suppose we have four matrices A. then we might think that E is a matrix whose columns con- sist of the second columns of A.2) = B. C. B. .4) = D.:. (The “3” denotes the third di- mension of ABCD. A. we enter >> ABCD = cat(j. 2. C. 1. C. and D. The solutions are given on page 163. >> ABCD = cat(3. for example.) And it is much easier than entering >> ABCD(:. B.. 2. B. However. and D ∈ R2×7 which we want to put into a three-dimensional array. use the colon operator to enter each row. This is easily done by >> ABCD = cat(3. Be Able To Do After reading this section you should be able to do the following exercises. 9 10 11 12 13 14 15 16 (a) Enter it in the following three ways: (i) type in all 16 elements directly.2. C. use the colon operator (and the transpose opera- tor) to enter each column. if we enter >> E = ABCD(:. and put the result back in the second 38 . [2 3 4 1]) is the same as >> BCDA = cat(3. For example. add it to the third row. (b) Multiply the second row of A by −9/5 .3) = C. We obtain a two-dimensional array by squeeze(E). . 2. 1. this is useful for putting arrays into a higher-dimensional array. B.1) = A. >> BCDA = cat(3. D] and cat(2. D. B. cat(1. D) is the same as [A. C. A. For example. not a two-dimensional array. >> ABCD(:. are to be placed in the new ordering. The command permute reorders the dimensions of a matrix.:. the second argument of permute shows where the original ordering of the dimensions. B. D) which concatenates the four matrices using the third dimension of ABCD. B..:.:) (where the array ABCD was created above). . If instead.

. (b) Show that the matrices you have obtained in (a) are correct by substituting the results back into the original formulas. Also. . B2 = A. . ∈ Rn×n . 3. Generate the tridiagonal matrix 4 −1 −1 4 −1 0 −1 4 −1 A= . Generate the matrix 1 2 3 A = 4 5 6 . 9. the next important topic is graphics. (c) Determine the average value of all the elements of R. en−1 (n − 1)2 −1 0 en n2 where the value of n has already been entered into MATLAB. 1 1 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 5 1 1 1 0 0 0 0 0 0 (a) Enter it using as few keystrokes as possible. . 16. 4. (d) Generate the matrix S where every element of S is the sine of the corresponding element of R. 5. Strings. (In other words. . 900)T using as few keystrokes as possible. . (a) Generate a random 5×5 matrix R. (e) Put the diagonal elements of R into the vector r. 3. 25. Do this all using one MATLAB statement. there are a number of minor topics which are useful in graphics and so we collect them here. don’t enter the elements individually. and Other Data Types Now that we have discussed scalar and matrix calculations. 3.. Strings. 39 .) (b) Zero out all the elements of A below the diagonal. . 7. . Enter the column vector x = (0. . Anonymous Functions. 2. 7 8 10 (a) Calculate a matrix B which is the square root of A. 1.. ∈ Rn×n . 4. . How- ever. calculate a matrix C each of whose elements is the square root of the corresponding element of A. 841. That is. −1 4 −1 0 −1 4 where the value of n has already been entered into MATLAB.) 6. . Anonymous Functions. . First.. don’t enter the elements individually. . Consider the matrix 1 1 1 1 0 0 0 0 0 −5 1 1 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 A= . Generate the tridiagonal matrix 1 −1 e1 4 −1 0 e2 9 −1 A= . and Other Data Types row. . (b) Determine the largest value in each row of R and the element in which this value occurs. . (In other words.

) The symbol @ is the MATLAB operator that constructs a function handle. The name “handle” is used in MATLAB to denote a variable which refers to some “object” which has been created.) However. * ). . finally. y. ). Second.* exp(-b. c) x. character strings are nec- essary in labelling plots. And. some graphics functions require that the name of a function be passed as an argument. that is.3. Thus. b. / ).. <arg2>. By the way.* or . 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. and exponentiation (i.* cos(3*t) and then evaluate it by ˆ >> x = [0:.1. It is also possible — although probably not very useful — to let g have one vector argument. Anonymous Functions anonymous functions allow us to easily define a function which we can then plot. 3.) ˆ Warning: It is quite easy to forget to put dots (i. (This is similar to writing a function or subroutine or subprogram in a high-level computer language.. < arg2 >. it can be written as one simple expression.. 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 ..1. and logical variables We might as well get all these out of the way at once. the name of this function is ans.e.* cos(c. .e. y. 3. y. c) = xa e−bx cos(cy) by >> g = @(x. b. 40 .e. If our function is f (< arg1 >. for example. we can think of an anonymous function as being created by (<argument list>) <expression> and the handle to the function (in C. text variables. Cell arrays are generally used to manage data and since structures are also used to manage data we also include them here. b.e. . say x = (x. a. if the mathematical function is particularly simple. the address of the function) being returned by using @. cell arrays are occasionally helpful in labelling plots.*x) . For example..) <expression> For example.* exp(-2*t) .. a . a. structures. Third. . division (i. cell arrays. “ . integers. Anonymous Functions In MATLAB it is common to define a mathematical function in a separate file as we discuss in Sec- tion 8.*y) ˆ in which case any of the input arguments can be in R or in Rn . we can create a function handle to a MATLAB function by. if f is defined by >> f = @(t) t 5 * exp(-2*t) * cos(3*t) ˆ then ˆ >> f(3) is allowed. Another reason is that there are a number of data types in MATLAB including floating-point vari- ables.) = < expression > the MATLAB statement is >> f = @(<arg1>. This is similar to a pointer in C which gives the ad- dress of a variable or of a function.”) before the mathematical operations of multipli- cation (i. we can define it in MATLAB using an anonymous function. we can define g(x. . a. we can define the function f (t) = t5 e−2t cos(3t) by >> f = @(t) t.01:1] 0 >> fx = f(x) >> A = rand(5) >> fA = f(A) More generally. 5 .

If the variable does not appear in the argument list. the function could have been defined equally well by >> t = @(w o ) = heaviside(w o + 1) . For example. then its value is ..4 It is even possible to define a piecewise function in this way.e. i. Or. We give an example where this is very useful in Section 3. i. in other words. in MATLAB. the x is independent of any other x which appears in the code..heaviside(x .*(1 .abs(w o )). the piecewise function 1 − |x| for x ∈ [−1.2. Note: The x in “ @(x)” is a dummy variable.*(1 .1)). 3. +1] t(x) = 0 otherwise. is >> t = @(x) (heaviside(x + 1) .abs(x)). an isosceles triangle with the length of the base 2 and the height 1.1).e. 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. Passing Functions as Arguments >> f = @cos so that f(3) is the same as cos(3).heaviside(w o .

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.xed when the function is defined. For example. Thus. >> h(5) returns 50 and so does >> r = 0 >> h(5) Warning: Don’t forget that if a variable does not appear in the argument list. then its value is .

* exp(-2*t) . 3. i.* cos(3*t) ˆ is “more similar” to f (t) = t5 e−2t cos 3t. .e. 0 t 0 ) ) ˆ is equivalent to the f defined above but does not require you to remember all the dots. the func- tion f defined above can also be defined by >> f = inline( 0 t. .. something like 41 . * ).e. . the MATLAB command vectorize does it for you.e. Passing Functions as Arguments Warning: This is a very important section — read it carefully and understand it. and exponentiation (i.* cos(3*t) 0 .. / ).) Since it is quite easy to forget to put dots (i. 5 . division (i.. something like >> ezplot(sin) (you are trying to generate an “easy plot” of the sine function) and you get a strange error message. For example. < arg2 >. To continue the first example. 0 <arg1> 0 .. ). .) = < expression > the MATLAB statement is >> f = inline( 0 <expression> 0 .e. 0 <arg2> 0 .* exp(-2*t) . 0 t 0 ) ˆ In general.. 5 . . ˆ >> f = vectorize( inline( 0 t 5 * exp(-2*t) * cos(3*t) 0 . >> f = @(t) t. ) before the mathematical operations of multiplication (i. A function can also be defined — but don't do it —by the inline command. Warning: The inline command is obsolete and should not be used because it is slow and also because it is rather difficult to read. if our function is f (< arg1 >.e. inline is mentioned here only because it is often found in “old” codes...2. If you try to pass a function as an argument to another function.xed when the function is defined.

34]) returns ford. a substring can be easily extracted. enter >> str2 = [str 0 . >> fplot( 0 (x*sin(x) + sqrt(1 + cos(x)))/(x 2 + 1) 0 . [-5 +5]) % WRONG will not work. For example. To convert a scalar variable. you will know what you did wrong. i.3. [-5 +5]) % CORRECT Note: There are a number of “older” ways to pass function names. >> fplot( 0 fnc 0 . Character variables are handled the same as vectors or matrices. to see what is actually contained in the vector str enter >> str + 0 or >> 1*str Since str is a row vector.by Monty Python 0 ] or >> str2 = [str. use anonymous functions. we use fplot(@fnc. 0 *cos(x) 0 ] 42 . they perform some very useful tasks which are worth discussing now. and so converts the numerical value in each element into the corresponding character when it is printed out. now is a good time to discuss how characters are stored in MATLAB variables. or even a vector or a matrix. 2*pi. we can plot the function y = f (x) in the interval [−5.by Monty Python 0 ] (which might be easier to read). However. [-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. If fnc is a MATLAB function or a user-defined function m-file. 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. +5] by fplot(<function "name">. which is mainly designed to perform numerical calculations. num2str(c2).. ˆ 3. Instead. [-5 +5]) because f is a variable which we have already defined. 3. [-5 +5]) will also work. to a character variable use the function num2str. >> str(1:7) returns And now and >> str([9:11. then it is not known in the MATLAB workspace so fplot(fnc.3. to concatenate the two strings. suppose you enter >> x = linspace(0. 0 *sin(x) + 0 . to generate a new text variable which adds “– by Monty Python” to str. [-5 +5]) but don't do it! Instead. Strings Character strings are a very minor part of MATLAB. Since we discuss graphics in the next sec- tion. MATLAB knows that this is a text variable.e. For example. A string variable. Strings Error using sin Not enough input arguments. We can even pass a “simple” function by. For example. but its handle. For example. If f has been defined by an anonymous function. 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. for example. For example. not a “regular” row vector. It is sometimes necessary to pass the name of a function into a MATLAB function or a function m-file created by the user.1. then we enter fplot(f. 0 . as we discuss in Section 4. It is often important to combine text and numbers on a plot. For example. This can be done by >> s = [ num2str(c1).

which we discuss next. A cell array generalizes the “standard” arrays which were discussed in the previous section.) 3. (An optional second argument to num2str determines exactly how the number or numbers are to be printed. each row must have the same number of elements and so we have to pad all but the longest row. The argument can also be a vector or a matrix string. One simple reason for this is that it is easier to pass all the data into and out of functions.e..4. If desired. The primary difference between a cell array and a structure is that in a structure the elements are named rather than numbered.. you can have more control over how data is stored in strings by using the sprintf command which behaves very similarly to the C commands sprintf. Cell Arrays and Structures It is occasionally useful in MATLAB to have a single variable contain all the data which is related to a specific task — and this data might well consist of scalars. but this is usually not needed.)) displays it on the screen. 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. (It can also be used with cell arrays of strings. there may be a worry that a string has leading or trailing blanks.. For example.) Note: We do not usually enter matrices this way.) A text variable can also contain more than one line if it is created as a matrix. (See fscanf for more details. sscanf Behaves very similarly to the C command in reading data from a file using any desired format. we simply use “ . 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. Note that the data can be displayed directly on the screen by using disp.) generates a character string and disp(sprintf(. The argument can also be a vector or a matrix. but be- cause it is so seldom necessary. The elements of a “stan- dard” array are numbers. Cell Arrays and Structures without explicitly having to enter the values of c1 and c2. Instead.” to separate columns. i. (This is also very similar to the C command. >> Str = [ 0 And 0 0 0 now 0 0 for 0 something 0 0 completely 0 0 different 0 ] is four lines long. sprintf(. and printf. We consider this an advanced topic not because it is complicated.4. 0 go cells 0 . [1 2 3] 0 . That is. There also is a str2num command to convert a text variable to a number and sscanf to do the same with more control over how the data is read. strtrim(str) Removes all leading and/or trailing spaces in a string. and text variables. we will shortly show how to avoid this requirement. vectors and/or matrices.) sprintf Behaves very similarly to the C command in writing data to a string using any desired format. (Using cell arrays.) Occasionally. whereas the elements of a cell array can be any data type. Since str is a matrix. fprintf. 3.. str2num(str) Converts a string to a variable. either real or complex.. as discussed in Section 6. (See fprintf for more details. one column per line. It is also very similar to the fprintf command in MATLAB which is discussed in detail in Section 6. A simple example of a cell array is >> C = {2+3i. hilb(5) } 43 .) Some Useful String Commands num2str(x) Converts a variable to a string.

something 0 . In order to use c as a cell (if has been previously used as a non-cell). 0 different 0 } and obtain the i th row by >> Str cell{i.4.0000i] go cells 0 [3x1 double] [5x5 double] The only difference between this and a “standard” array is that here curly braces. .2) = { 0 go cells 0 } >> C(2. enclose the elements of the array rather than brackets. >> C(1. We will not discuss cells further except to state that cell array manipulation is very similar to “standard” array manipulation. Note that only the scalar and the text variable are shown explicitly. Cell Arrays and Structures and the output is C = 0 [2. The other elements are only described.j}. i..1) = {2+3i} >> C(1. >> c = pi >> c = 0 And now for something completely different 0 >> c(5. All the contents of a cell can be displayed by using the celldisp function. However.2} = hilb(5) It is important to understand that there is an important difference between C(i.3) = 17 redefines c twice without any difficulty.. 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. 3. 0 now 0 .e.1} = [1 2 3] 0 >> C{2. If you now try >> c{3} = hilb(5) MATLAB will return with the error message ??? Cell contents assignment to a non-cell array object.0000 + 3.e. a cell array can be preallocated by using the cell function.j) and C{i. 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 . }.2200e+02 . you have to either clear it using clear. ]. 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 43 where each string had to have the same length.2) = {hilb(5)} and a third way is by >> C{1.1} = 2+3i >> C{1. In addition. 0 for 0 . The th former is the cell containing element in the (i. [. or explicitly redefine it by using the cell function. For example.2} = 0 go cells 0 >> C{2. .5. .:} Note: It is even possible to sort a number of strings in lexicographical ordering by putting each string in a 44 . {. empty it using []. .1) 5 % WRONG ˆ returns an error message because a cell cannot be raised to a power whereas >> C{1. i.1} 5 % CORRECT ˆ returns “ 1.1) = {[1 2 3] 0 } >> C(2. j) location whereas the latter is the element itself. A second way to generate the same cell array is by >> C(1. just as a “standard” array can be preallocated by using the zeros func- tion. For example.9700e+02i”. 0 completely 0 . this cannot be done with cells.

4.1). but the data is stored by name. The cell array we have been using can be written as a structure by >> Cs. 0 go cells 0 . 0 vector 0 .text = 0 go cells 0 >> Cs... Cell Arrays and Structures separate row of a cell array and using the sort function. For example. The command fieldnames returns a cell array containing all the field names of a structure as strings. pi. hilb(5)) By the way. is a field of a particular structure. [1 2 3] 0 . 2+3i. 0 structures rule 0 . 0 matrix 0 . >> fieldnames(Cs) returns ans = 0 scalar 0 0 text 0 0 vector 0 0 matrix 0 and 45 .vector = [1 2 3] 0 >> Cs. for example.. 0 vector 0 .(sf) = hilb(10 Warning: As with cells. Structures are very similar to structures in C and C++ . 0 text 0 . Structures can store different types of data similarly to cell arrays.0000i text: 0 go cells 0 vector: [3x1 double] matrix: [5x5 double] The structure can also be created using one command by >> Cs = struct( 0 scalar 0 . The field names of a structure can be handled using the following two commands. 0 text 0 . rather than by number. >> sf = 0 matrix 0 >> Cs. >> Cs(2) = struct( 0 scalar 0 . .0000 + 3. which is stored in a string. 3. empty it using [].matrix = hilb(5) Typing >> Cs returns Cs = scalar: 2. ones(10. Thus.. hilb(5) 2) Now ˆ >> Cs returns Cs = 1x2 struct array with fields: scalar text vector matrix A field name can be stored in a string and used in the struct s by.scalar = 2+3i >> Cs. structures can themselves be vectors or matrices. 0 matrix 0 . you have to either clear it using clear. . The command isfield determines if a particular name. called fields . you cannot change a nonstructure variable to a structure variable. or explicitly redefine it by using the struct function. Instead.

Each character in a string is represented by two bytes because it can represent any Unicode UTF-16 character (although here we are only interested in ASCII characters).b(0) = 1. a structure variable is an instance of the struct class.b = @cos. which can all be instances of different classes. celldisp Display all the contents of a cell array. char: All strings are instances of the char class.. getfield Get one or more values of a structure field. logical: We will discuss logical variables in Section 8. but it can contain any number of fields. We have already described a number of fundamental classes. struct Create a structure with specified fields and values. @cos.5. we can even store anonymous functions in cell arrays and structures. An important point to remember is that a variable in most pro- gramming languages is a single quantity.5) Each element of C ∈ R2×2 has the logical value 1. but a simple example is >> A = rand(2) >> C = (A > . For example. orderfields Order the fields of a structure to be in ASCII order. Cells and Structures cell Preallocate a cell array of a specific size. Alternately. Tr. double: By default any variable that is given a numerical value is a double precision floating-point number. suppose you want to work with all six basic trig functions.1. For example.e. The OOP capabilities of MATLAB are similar to those in C++ and Java. but they are now commonly called classes — which is a central concept in object- oriented programming (OOP). They can also be stored in a structure by >> Tr. whereas in MATLAB it is a vector or a matrix or an array of quantities. not an integer class. Advanced Topic: Data Types and Classes >> isfield(Cs. i. They can be stored in a cell array by >> T = {@sin. which can all be instances of different classes. first we discuss the “fundamental” classes in MATLAB.a = @sin. fieldnames Return all field names of structure.c = @tan.d = @cot. Advanced Topic: Data Types and Classes A MATLAB variable can have a large number of different types of values. Tr. @(x) exp(exp(sin(x)))} is allowed — but probably not very interesting.e = @sec. so that Tr. @sec. @(x) exp(sin(x)). cell: A cell variable itself is an instance of the cell class. < fieldname >= value. However. Tr. These values used to be called data types. rmfield Remove one or more fields from a structure. We will discuss some of these capabilities at the end of this subsection. isfield Determine if input is a field name of the structure. setfield Set one or more values of a structure 3. Tr. @tan. @cot. Note: We cannot store function handles in standard matrices — we can only store numbers. each field can be given a value by < struct > . but it can contain any number of ele- ments. We can also use function handles in cell elements and structures. true. the variable x which is defined by x = 1 is an instance of the double class. function handle: This provides a means to call a function indirectly.5. For example. >> C = {@sin. 0 vector 0 ) returns 1. struct: Similarly. and we first discuss those which occur frequently in this tutorial. @csc} so that T{2}(0) = 1. 3. Tr. Incidentally. if the corresponding element of 46 .f = @csc.

we now list them all. and aj = 127. similar to classes in object-oriented programming lan- guages. false.e.. which is an instance of the int8 class. For example. >> class(i) returns int32 and >> isa(i. For completeness. You can also determine if a variable has a particular class by using isa. A simple template for generating a new class is 47 . otherwise. These logical values are each 1 byte. the results of >> a = 5. i. to obtain an instance of the single class you can enter A = single(rand(5)) The same technique holds for all the numerical classes. Advanced Topic: Data Types and Classes A is > . Warning: Caveat Emptor! The procedures for combining different numerical classes is very different from other programming languages. MATLAB has user-defined classes. To determine the class of a variable. Continuing the previous example. which is an instance of the int32 class. each in the form of a matrix (from a 0×0 matrix up to an n dimensional matrix for any n ). 3. use the function class. Fundamental Classes double double precision floating-point number (8 bytes) 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) char string (each character is 2 bytes) logical logical (true or false) (1 byte) cell its elements can be instances of any classes and sizes struct its fields can be instances of any classes and sizes function handle allows indirect references to functions For example.5 and value 0.5 >> i = int32(3) >> j = int8(127) >> ai = a + i >> aj = a + j are ai = 9.5. MATLAB has 15 fundamental classes. In addition. 0 int8 0 ) returns 0.

. Then add one to the serial number. function ??? ... end.6... end end To define a class which is a subclass of another class.. end methods % define the methods used in this class function ??? . You create a handle class by classdef <class name> < handle where handle is an abstract class.e. Listener objects then execute fuctions.. When an event is “triggered”. a notification is broadcast using the event name.... any and all copies of an object use the same fields as the original object.2): π 10.. i. “rank”... A particular event is attached to an event name. 1). ˆ (1...name = ???. 3..6. 1. The solutions are given on page 163.. 2) which is in the cell element (1..e.1): the string “Hilbert”. Only a handle class can define events and listeners. and “serial number”. (2. Generate a structure with the fields “name”. end .. i. i... 1) .e. inside events .) Classes class Determine the class of a variable.. ˆ (2. enter classdef <class name> < <superclass name> There are two kinds of classes in MATLAB: handle classes and value classes. (a) Generate a 2×3 cell array with the following elements: (1. Be Able To Do After reading this section you should be able to do the following exercises. (2.. Put something appropriate in each in two ways: (1) directly. In a value class each object has its own unique fields.2): the function handle for the function sin e x. Be Able To Do classdef <class name> % name the class properties % determine the properties and set their access ... (An event is some change or action that occurs in an object of a handle class... (1.. end function ??? . 48 . when an event name is broadcast. s.3): this is the square of the matrix in (1. isa Determine whether a variable is an instance of a particular class.3): the logical value true..1): a uniform random matrix of size 5. called callbacks. 2. and (2) using the struct command.. (b) Square the value of the element (1.. In a handle class all in- stances of the class refer to the same data. 3. end end events .

you want to plot y3 = sin cos(x2 − x) for x ∈ [0. 2) at x = 5. these images can be output from MATLAB and printed on a wide variety of output devices. 4. First. For example. n). 2π]. Note: Most MATLAB commands which take vectors as arguments will accept either row or column vec- tors. In addition. 2π] n 0 otherwise.xx ) ). more advanced graphics commands are discussed in the next section. <number of points>) so it is much harder to make a mistake. The linspace command has two advantages over the colon operator: (1) the endpoints of the axis and the number of points are entered directly as >> x = linspace(<first point>.and three-dimensional plots using simple and flexible commands. y3) Note that the axes are changed for every plot so that the curve just fits inside the axes. >> y2 = exp(cos(x)). All graphical images are generated in a “graphics window”. y) = sin(x + y) cos(x − y). y1) >> plot(x.1. and (2) round-off errors are minimalized so you are guaranteed that x has exactly n elements. 2 . this demo makes it quite easy to generate your own graphics. >> y3 = sin( cos( xx. x3 (b) f (x) = x1 − ex2 + cos . and its first 49 . >> x = 2*pi*[0:n-1] 0 /(n-1). 2*pi. generate n data points on the curve by >> n = 100. |x1 + x2 | + 1 (c) f (x) = 1 − cos x for x ∈ [0.1. We be- gin by considering only the basic commands. non-graphical and graphical commands can be completely intermixed. >> xx = linspace(0. 8]. We can generate the x coordinates of the data points more easily by >> x = linspace(0. sup- pose you want to plot the functions y1 = sin x and y2 = ecos x for x ∈ [0. Hint: Use the heaviside function. including color ink-jet printers and black-and-white and color laser printers. Graphics A very useful feature of MATLAB is its ability to generate high quality two. also. We plot these data points by ˆ >> plot(x. 8. Graphical images can be generated both from data calculated in MATLAB and from data which has been generated outside of MATLAB. You also can have very fine control over the appearance of the plots. y2) >> plot(xx. Two-Dimensional Graphics The MATLAB function plot is used to constructing basic two-dimensional plots. >> xx = 8*[0:n-1]/(n-1). 3. which is completely separate from the “text window” in which MATLAB commands are typed. Use anonymous functions to define (a) f (x. Two-Dimensional Graphics Evaluate the function in the cell element (2. 4. <last point>. Thus. >> y1 = sin(x). n). 4. There are a number of demonstrations of the graphical capabilities in MATLAB which are invoked by >> demo Since the MATLAB commands which generate the plots are also shown.

) This is why we used the statement >> x = 2*pi*[0:n-1] 0 /(n-1). the output of [0 : 0. y2.02-eps] is 0 0. xx. dashed line o circle b blue (0 0 1) : dotted line * asterisk y yellow (1 1 0) -. y2. solid line (default) + plus sign g green (0 1 0) -. y1) Customizing Lines and Markers Symbol Color (R G B) Symbol Line Style Marker Description r red (1 0 0) . 0 :* 0 ) These strings are used to modify the color of the line. the colors are defined by giving the intensities of the red. y1. you can use small asterisks to show the locations of the data points for the y3 curve by >> plot(x. dash-dot line . you can change the type of lines by >> plot(x. and blue components in that order. y2. y3. x.) Note: The plot function can even have only one argument. y2. 0 -. green. to put markers at the nodes. y3. x. 4. (We list all these symbols in the following table. (For example. dashed line with circles at the data points. 0 g--o 0 . (As we discuss later in this section. entering >> plot(y1) will result in a plot which is equivalent to >> plot([1:length(y1)].0100. the second is a a green. and then the third by † As we discussed previously. which does not suffer from round-off errors because the colon operator is only applied to integers.1. x.0 . >> plot(x. 0 : 0 ) where “ --” means a dashed line and “ :” means a dotted line. y1. above. and then add the second. 50 . y3) Each curve will be a different color — but this will not be visible on a black-and-white output device. point m magenta (1 0 1) x cross (a deep purplish red) s square c cyan (0 1 1) d diamond (greenish blue) upward pointing w white (1 1 1) ˆ triangle k black (0 0 0) v downward pointing triangle > right pointing triangle < left pointing triangle p pentagram h hexagram For example.0 .) In addition. y3. solid line. x. type >> plot(x. x. y1. For example. xx. 0 r 0 . and to modify the type of line as shown in the table below. We can also plot the first curve. 0 mp 0 ) plots three curves: the first is a red. y1. Instead. the third has magenta pentagrams at the data points but no line connecting the points. Two-Dimensional Graphics and last elements are exactly the values entered into the command. xx. it is very unlikely (but it is possible) that round-off errors might cause the statement >> x = [0: 2*pi/(n-1): 2*pi] 0 .01 : 0.† To put all the curves on one plot. to return n − 1 elements rather than n. 0 -.

. each of which has a Gaussian shape with half-width w. plot(xx.† We also briefly digress to suggest another possible use for the plot command: making an animation. you may not be able to see it. >> hold on >> semilogy(xx. (The initial hold off is always a good idea if you later use hold on.1. not the semilog plot which is desired. Two-Dimensional Graphics >> hold off % this is a good idea before a ’hold on’ >> plot(x. It is particularly beneficial to put this before the first plot command in a script M-file: it cannot do any harm. However. We briefly digress to present a technical — but very important — detail. For example. and it will make the plot visible if it is already hidden. while if there is a graphics window. it is easy in MATLAB to simulate the time evolution of some function by repeatedly using plot. 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.6 we will discuss how to make a real movie. If a plot is hidden (possibly because you have been typing in the workspace and have raised the MATLAB window above the graphics window. 10. This is a very useful command because plots are frequently hidden. then this command is equivalent to figure(gcf). In Section 4. However. i. t) = ak e− k=1 for x ∈ [0. 4. The command >> shg raises the current graphics window above all other windows. 51 . y1) >> hold on >> plot(x.) Warning: Do not place the hold on command before the first plot. but this rapidly becomes unwieldly. exp(xx)). y3) Note that the axes can change for every new curve. We discuss figure and gcf in advanced subsections. We have just discussed how to put multiple curves on a plot. Instead. where the k th mode has amplitude ak and speed ck . This is a sum of k modes. entering >> xx = linspace(0. just replace one plot by another.e. This can lead to very strange results because certain parameters have already been set. or because there are some other windows visible on your terminal). exp(xx)) results in a linear plot. For exam- ple. 1001). all the curves appear on the same plot. 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. y2) >> plot(xx. L].

Of course. nr points). >> axis([-1 10 -4 4]) The general form of this command is axis([xmin xmax ymin ymax]). you might want to put a number of curves individu- ally in the graphics window. You can change the endpoints of the axes by. ˆ ˆ c = [1:nr modes] 0 . and meshgrid will be discussed in the next subsection. Warning: If you are comparing a number of plots. [X. You can “bounce” between these different rectangles by calling subplot repeatedly for differ- ent values of p. but now apply only to this particular rectangle in the graphics window. Two-Dimensional Graphics %%%%% script m-file: running gaussians a = . 0 r* 0 ) axis([0 L 0 max vert axis]) title(t) drawnow end where ak = 1/k and ck = 1/(2k − 1). [left bottom width height]). plot(x. 1. causes the plot to be repeated for the times [0:del time:max time]. 3). the maximum value of each mode is shown by the red asterisks which fly across the plot. >> subplot(’Position.*f(X . The commands axis and title will be discussed shortly. you can use the pause command (discussed in Section 8. you can determine the endpoints of the current plot by >> v = axis v(1) and v(2) are the minimum and maximum values on the x axis.L/2). C] = meshgrid(x.5]) is the same as subplot(2. The for loop. c). for t = 0:del time:max time ast x = mod(c*t + L/2. and v(3) and v(4) are the corre- sponding values on the y axis. del time = . which will be discussed in Section 8.3) to make all the plots visible. The axis command (discussed below) can then be used to rescale all the plots. Also. 4./(2*c-1). g = @(t) sum(R. nr modes).C*t)).1. You can also position the plots anywhere in the figure by subplot( 0 Position 0 . 52 . f = @(x) exp(-(mod(x. . 2. In addition. In addition. nr points = 1001.5 . nr points).95*max vert axis. L) .5.7*max vert axis. nr modes = 20. 10. R = repmat(1. ast y. for example. Otherwise your brain has to try to do the rescaling “on the fly” — which is very difficult. You can display m plots vertically and n plots horizontally in one graphics window by >> subplot(m. L = 10. whereas pause(time) pauses execution of the code for the given time. If you only want to set some of the axes. it is important that the endpoints of the axes are the same in all the plots. All the graphics commands work as before. p) This divides the graphics window into m×n rectangles and selects the pth rectangle for the current plot. set the other or others to ±Inf ( −Inf if it is the minimum value and +Inf if it is the maxi- mum). The command drawnow is very important because otherwise the graphics window will be blank until the final plot. you frequently do not know how large the axes need to be until you have filled up the entire graphics window. L). x = linspace(0. ast x. g(t). you can force the two axes to have the same scale by † Alternatively. max time = 100.1.01. For example. [0 0 . 2 / a 2). n. ast y = linspace(. max vert axis = 3. drawnow draws each new plot as fast as possible.† Instead of putting a number of curves on one plot.

We will show some examples shortly. while in the latter f(x) is evaluated for vec- tor values of x. <limits>) where the function is usually generated as an anonymous function or a MATLAB function or a user gener- ated function m-file (as described in Section 8. use the doc command.1. <limits>) For example. >> ezplot(f) ˆ ˆ ˆ ˆ ˆ plots the lemniscate of Bernoulli (basically an “∞” symbol). the error message Warning: Function failed to evaluate on array inputs.3). y) (x 2 + y 2) 2 . f (x. which is more general than fplot. <fnc 2>. +2π] enter >> ezplot(<function handle>) To include limits (as with fplot ) enter >> ezplot(<function handle>. Two-Dimensional Graphics >> axis equal or >> axis image and to have the same length by >> axis square To learn about all the options for these commands. so it must be called for every plot (unless hold on has been invoked). semilogy for a linear axis in x and a logarithmic axis in y. vectorizing the function may speed up its evaluation and avoid the need to loop over array elements. You then have complete control over how to plot the curve using the plot function. This function uses adaptive step control to generate as many data points as it considers necessary to plot the function accurately.. >> f = @(x. You can also store the data points calculated by >> [x.y 2). y) = 0. when using ezplot care must be taken if f is evaluated in a function m-file. a parametrically defined function can be plotted by >> ezplot(<fnc 1>. They can have problems with sharp peaks and asymp- totes and other “strange behavior”.e. i. Note: Recall in Section 3. Warning: These commands do not always generate the correct curve (or curves) because they know nothing of the actual behavior of the function. Note: The command axis is generally only in effect for one plot.(x 2 . will be generated 53 . There is an important difference between >> fplot(f. this command can also plot an implicitly defined function. y] = fplot(<function handle>. which can be executing by simply entering >> fplot(<function handle>. The limits are either [xmin xmax] in which case the y-axis just encloses the curve or [xmin xmax ymin ymax] in which case you are also specifying the endpoints on the y-axis. The plot command generates linear axes. Every new plot turns it off. To generate logarithmic axes use semilogx for a logarith- mic axis in x and a linear axis in y. by >> ezplot(<2D fnc>. [-5 5]) In the former f(x) is only evaluated for scalar values of x. To plot a function on the interval [−2π. If f(x) cannot be evaluated for vector values. <limits>) Finally. MATLAB has two different commands to plot a function directly rather than plotting a set of points.2 we discussed how to pass a function as an argument. [-5 5]) and >> ezplot(f. The first command we discuss is fplot. and loglog for logarithmic axes in both x and y. <limits>) In addition. The other command which can plot a function is ezplot. <limits>) rather than having the function plotted directly. Warning: Be particularly careful when plotting implicit functions because they can be really nasty and occasionally ezplot may not get it right. Thus. 4.

10). type >> hist(x. in >> f = @(x) log(x) + 1. To plot a histogram of the data stored in the vector x. type >> x = rand(100000.01). [-2*pi +2*pi]) >> ezplot(f) the vertical axes are different and ezplot is missing part of the curve. The two we discuss here are histograms and error bars. to see how uniform the distribution of random numbers generated by rand is./ (x. 0 Parrot Sketch 0 } results in a two-line title. Entering >> xlabel(<string>) >> ylabel(<string>) >> title(<string>) put labels on the x-axis. 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 .1. Two-Dimensional Graphics fplot and ezplot do not always generate exactly the same curves. 2 + 0. 4. in f = @(x) x 3/(x 2 + 3*x . Note that a title can contain more than one line as was discussed in Section [Macro:[text: cell]chap]. If you rerun this command a number of times. >> hist(x) To draw a histogram with a different number of bins. Finally. ˆ >> fplot(f. 1). Also. There are also a number of ways to plot data. you can fix the endpoints of the histogram by 54 . and on top of the plot. type >> hist(x. There is also an “easy” command for gener- ating polar plots. 0) where it plots the real part of log x while ezplot only plots the function for x ∈ (0. To avoid this “instability”. >> fplot(f. The first uses a “standard” array and so requires all the rows to have the same number of columns. we are interested in a different point. [-10 +10]) the function blows up at x = −5 and 2 and part of the curve for x ∈ (−5. For example. there are specific commands for each of these. [-2*pi 2*pi]) >> ezplot(f) fplot generates a spurious plot for x ∈ [−2π. Since you often want to label the axes and put a title on the plot. namely ezpolar. 1). Polar plots can also be generated by the polar command. whereas the latter two use a cell array and so each row can have a different length. Clearly you need more random numbers to get a “good” histogram — but. at the moment. type >> x = randn(100000. 2π]. <number of bins>) and to draw a histogram with the centers of the bins given by the vector c. in addition to the commands discussed above. >> hist(x) which generates random numbers with mean 0 and standard deviation 1. type >> hist(x) which draws ten bins between the minimum and maximum values of the elements in x. respectively. you will find that the endpoints of the histogram fluctuate. on the y-axis. to see how uniform the distribution of Gaussian random numbers generated by randn is. For example. ˆ ˆ ezplot(f. 2) is not shown. c) As another example. in >> f = @(x) x .

we must rescale the histogram so that its area is 1. 0 hist 0 ) Note that output variables from hist are reversed when input to bar.000. >> area = sum(nr each bin)*dx % or area = nrdata*dx To plot this rescaled histogram. l. e) Sometimes the error bars are not symmetric about the y values. (If desired. Another way to calculate c. For example. ad- ditionally. y) which can also be considered to be the plot of a step function. >> hist(x) In order to compare the histogram with the density function. If it has mean µ and standard deviation σ. If you now rerun this code you will see a much smoother histogram. >> c = xmax*[ -1+1/nrbin : 2/nrbin : 1-1/nrbin ]. >> nrdata = 100000. and nrdata. The numbers in each line must be separated by com- mas. 4. >> hist(x. nr each bin/area. we have just discussed the Gaussian distribution.) The load command can also be used to read a matrix into MATLAB from a separate data file. These commands are discussed in detail in Section 6. 1). >> nrdata = 100000. say to 100. to get a “good” histogram you should increase nrbin. The matrix is input by 55 . To generate a random sequence use >> mu = 5. say to 100. nrbin). >> sig = 2. but it does not complete the rectangle. which are similar to their C counterparts. then the density function is (x − µ)2 1 f (x) = √ exp . For example. draws such a curve. u) Note: All the elements of l and u are non-negative. 1). The command csvwrite writes the elements of a matrix into a file using the same format. The difference between this command and csvread is that the numbers can be separated by commas or semicolons or by spaces. 2πσ 2 2σ 2 R +∞ where −∞ f (x) dx = 1. which might be clearer. say x again. The command >> stairs(x. We have already seen how to plot the vector x vs. >> M = csvread( 0 <file name> 0 ) reads in data from a file one row per line of input. >> x = randn(nrdata.) Thus. y. To find its area enter >> nr bin = 1000. >> [nr each bin. This is done by >> errorbar(x. The data must be stored in the data file one row per line. In this case. you need vectors l and u where at xi the error bars extend from yi − li to yi + ui .1. A histogram shows the frequency of values in a vector. the vector y by using the plot command. A stairstep graph is similar in that it draws the continuous curve describing the maximum of the histogram. >> x = mu + sig*randn(100000. c) Note that c contains the midpoints of each bin and not their endpoints. >> dx = x center(2) . you can have much more control over how data is input and output by using the fscanf and fprintf commands.x center(1). xmax-xmax/nrbin. enter >> bar(x center. is >> c = linspace(-xmax+xmax/nrbin. which returns the number of elements in each bin as well as its midpoint. you have an error bar of size ei for each point yi . Data can also be entered into MATLAB from a separate data file. Two-Dimensional Graphics >> xmax = 4. x center] = hist(x. you can plot the curve connecting the data points along with the error bars by >> errorbar(x. >> nrbin = 20. A histogram shows a graphical image of discrete data by stacking rectangles next to each other. (The histogram is not plotted because the results are output. nr bin). Of course. but suppose we want to compare this histogram to an actual probability density function. If. y. The data can then be plotted as desired.

the number of rows of M is the largest of the number of elements in any row of the file and missing data are replaced by NaN’s. If desired. For example. >> file = 0 <file name b&w> 0 .) If you want to save a file in postscript. containing the elements of a matrix and enter it into MATLAB using >> load mymatrix.. >> clear saves all the variables to the file allvariables. Or you can enter >> M = load( 0 <file name> 0 ) and the data is stored in the matrix M. you can save it in black-and-white postscript by >> print -deps <file name b&w> or in color postscript by >> print -depsc <file name color> There is a minor.† This can also be done by >> M = importdata( 0 <file name> 0 ) which had the added advantage that there does not need to be an equal number of data in each row. in the file name). the colors are converted to different grayscales. file) † The load command is a little tricky because it can read in files generated both by MATLAB (using the save command) and by the user.dat. Note: The print command is also a MATLAB function where it is called by >> print( 0 -deps 0 .dat you obtain a new matrix. if you create a file. drop the extension. There are an innumerable number of printer specific formats that can be used. This makes it possible to differentiate lines and/or regions. 0 <file name b&w> 0 ) The advantage of using the print function is that the arguments can be variables. >> print(device.mat. If not.mat in binary format and then deletes all the variables. all the non-white colors in the plot become black. When the black-and-white file is printed.e. Two-Dimensional Graphics 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. However. say mymatrix. if any. but important. 4.mat loads all these variables back into MATLAB using the binary format. Thus. (See help print or doc print for details. when the color file is printed. 56 . An oversimplified example is >> device = 0 -deps 0 . Graphics can also be easily printed from within MATLAB. the load command determines how to read a file depending on the extension. which contains these elements. On the other hand. the plot can be sent to a file rather than to an output device. called mymatrix. >> clear or >> save allvariables. >> save allvariables. You can print directly from the graphics window by going into the “File” menu item. Entering >> load allvariables or >> load allvariables. difference between these two files if they are printed on a black-and- white laser printer. You can also store the plot in the text window by using the command print.1.

num2str(i). file) >> . . print Prints a plot or saves it in a file using various printer specific for- mats. >> print(device. Two-Dimensional Graphics It is oversimplifed because there is no need to use three lines when one will do. Input-Output csvread( 0 <file name> 0 ) Reads data into MATLAB from the named file. csvwrite( 0 <file name> 0 . However. >> file = [ 0 fiddlededum 0 . if many plots are to be printed then the print device can be changed once rather than in every print command. one row per line of input. print -deps <file name> saves the plot in the file using encapsulated PostScript (so it can be plotted on a PostScript laser printer).eps 0 ]. the numbers in each line must be separated by commas. . For example. 0 . one row per line of input. num2str(i). The name of the resulting matrix is <file name>.eps 0 ]. .1. importdata( 0 <file name> 0 ) Similar to load but there need not be the same number of elements in each row. Also. 4. A) Writes out the elements of a matrix to the named file using the same format as csvread. >> i = i + 1. the numbers in each line can be separated by spaces or commas. file) >> . 0 . >> print(device. load( 0 <file name> 0 ) Reads data into MATLAB from the named file. . >> file = [ 0 fiddlededum 0 . if you are printing many plots then you can easily modify the file names as in >> i = 1. 57 .

drawnow Update the current figure (which is frequently not done if MAT- LAB is executing further commands). plot(z) plots the imaginary part of z vs.. subplot(m.. mark. y1.y) Plots a stairstep graph. If z is complex. i. l.) where s1. s1... s2. x2. c) lets you choose the midpoint of each bin. loglog The same as plot but both axes are logarithmic. i. the index number of the elements.. Three-Dimensional Graphics Two-Dimensional Graphics plot(x. i. y) = 0.2. p) Divides the graphics window into m×n rectangles and selects the pth rectangle for the current plot. hist(x. y. e) The first plots the data points x vs. Some additional arguments that can be used: plot(x) plots x vs. plots a step function. 4. x(t).e. n) Generates n equally-spaced points between a and b (inclusive). s2. . <fnc 2>) f (x).). f (x.Y) plots each column of Y vs. to generate a helix 58 . or ezplot(<2D fnc>) an implicit function. The limits can <limits>) be [xmin xmax] or [xmin xmax ymin ymax]. o errorbar(x. the index number of the ele- ments. are optional character strings containing information about the type of line. title(<string>) Puts a title on the top of the plot. The general form of this command is plot(x1. the real part. or creates a new graphics window if none exists. Limits can also be specified if desired. stairs(x. Three-Dimensional Graphics The MATLAB command plot3 plots curves in three-dimensions. Plots the specified function within the limits given. x. xlabel(<string>) Puts a label on the x-axis. shg Raises the current graphics window so that it is visible. n. y... ezplot(<function handle> Generates an “easy” plot (similar to fplot ) given the function ) ezplot(<fnc 1>. hist(x. For example. rectangles can be placed anywhere inside the window by subplot( 0 Position 0 . <number of bins>) changes the number of bins. n) Generates n logarithmically spaced points between 10a and 10b . fplot(<function handle>. axis equal and axis([xmin xmax ymin ymax]) are two common uses of this command. y with error bars given by e. hold Holds the current plot ( hold on ) or release the current plot ( hold off ).e. In addition. hist(x) Plots a histogram of the data in a vector using 10 bins. The endpoints of the current plot are returned by axis (i. logspace(a. and color to be used. semilogy The same as plot but the y axis is logarithmic. plot(Y) plots each column of Y vs. . theta) Plots the data points in polar coordinates. b. polar(r. y2. ezpolar(<function handle>) Generate an “easy” polar plot of r = < functionname >(θ). . b.2. axis Controls the scaling and the appearance of the axes. linspace(a. 4.e.. It can also plot a parametric function. with no arguments). y) Plots the data points in Cartesian coordinates. y(t) . semilogx The same as plot but the x axis is logarithmic. ylabel(<string>) Puts a label on the y-axis. . errorbar(x. u) The second plots error bars which need not be symmetric about y.e. plot(x. .

>> s = sin(t). 20*pi. 20*pi. the underlying mesh must be created. >> plot3(t. you can put a label on the z-axis by >> zlabel(<string>) There is also an “easy” plot3 command. t) and to generate a conical helix enter >> t = linspace(0. Three-Dimensional Graphics enter >> t = linspace(0. t) Also. >> c = cos(t). you change the domain of t by specifying the additional argument [tmin. y) in three-dimensions with the hidden surfaces removed. >> plot3(c.*s. 1001). t. >> s = sin(t). It generates the curve x(t). z(t) for t ∈ (0. y. >> c = cos(t). 2π) by >> ezplot3(x. 2001). The easiest way is to use the command meshgrid. This combines a discretization of the x. MATLAB also plots surfaces z = f(x. s. y(t).2. and z have been defined using anonymous functions. Again. tmax]. z) if x.*c. First. 4. y.

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 x–y 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 command, 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 x–y 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 x–y plane toward the +z axis (so 0◦ is in the x–y 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 command. 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

**ezcontour, ezcontour3, ezmesh, and ezsurf.
**

A surface can also be plotted in polar coordinates. For example, the code which plots

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

0 Color 0 . 0 Color 0 . Z) Plots a contour in 3-D..) where . . Z) Plots a 3-D surface using a wire mesh.3.. The general form of this command is plot(x1. <elevation>) or view([x y z]). ’?... y) Same as meshgrid except that the two arguments are reversed. Y. 0 PropertyName 0 .. meshgrid(x.) where s1.3. ezcontour(<2D fnc>) Generates an “easy” contour looking down the z axis. contour3(X.. n. ezmesh(<2D fnc>) Generates an “easy” 3-D surface using a wire mesh. subplot(m.. Note: The demonstration program shows many more of the graphics capabilities of MATLAB.. y) Generates a 2-D grid given the x-coordinates and the y-coordinates of the mesh lines. ’?’ – where ? is a single character denoting one of the colors in the table. LineSpec. b] – where this denotes the color by giving its red. y. Z) Plots a contour looking down the z axis. We have already discussed plot(x. Z) Plots a 3-D filled-in surface. z1. ezcontour3(<2D fnc>) Generates an “easy” contour in 3-D. Y. Z) Plots a filled contour. y. . Advanced Topic: Commands In the previous subsections we have discussed how to use “simple” graphics commands to generate ba- sic plots. Here we discuss some of the more useful advanced features. z2. y) and plot(x. its width. The three names and values we discuss refer to the color of the line. <fnc 2>. . s2. Y. . Addition- ally. pol2cart(Th. contour(X. Enter demo and then in Help Navigator click on Graphics. x2. green. First. 4. Generates an “easy” plot in 3-D.. and blue intensities in the 61 . 4. y. axis([xmin xmax ymin ymax zmin zmax]) changes the endpoints of the axes. you can use >> plot(x. view Changes the viewpoint of a 3-D surface plot by view(<azimuth>. contourf(X.) or >> plot(x. LineSpec) where LineSpec contains one or more symbols which customize the line. mark. • 0 Color 0 . We divide the topic into two subsections: the first discusses the commands themselves and the second discusses how to change some of the properties of these commands. <fnc 3>) mesh(X. z) Plots the data points in Cartesian coordinates. MATLAB can also do much more “interesting” graphics. we want to return to the plot command. PropertyValue. and even publication quality graphics.?’ – where ?. y2. . . p) Remember than subplot can also be called in 3-D to put a number of plots in one graphics window. axis Controls the scaling and the appearance of the axes. however. [r. and color to be used. s1. indicates that there can be more property names and values. ezplot3(<fnc 1>. Y. are optional character strings containing information about the type of line. zlabel(<string>) Puts a label on the z-axis. ezsurf(<2D fnc>) Generates an “easy” 3-D filled-in surface. PropertyValue. 0 PropertyName 0 .? is the long name of one of the colors. There are a huge number of prop- erties which can be used. ndgrid(x. clabel Label contour lines generated by contour or contour3. s2. y1. Y. Advanced Topic: Commands Three-Dimensional Graphics plot3(x.. and the size of any markers. surf(X.. y.. R) convert polar to cartesian coordinates. g.

3. For example. To terminate this command press the return key. It is possible to obtain the current position of the cursor within a plot by using the ginput command. To enter exactly n positions. You can also use the mouse to place text inside the plot using >> gtext(<string>) The text is fixed by depressing a mouse button or any key. <string2>. Alternatively. For example. ) Each string appears on a different line preceded by the type of line (so you should use as many strings as there are curves). y] = ginput(n) You can terminate the positions at any time by using the return key. respectively For example. use >> [x. including Greek letters. .5 • 0 MarkerSize 0 . <string>) The text is placed at the point (xpt. Text can be placed anywhere inside the plot using >> text(xpt. . 2*pi. try “\beta{}f(x)” instead.e. but not quite identical. enter >> doc text and then click on the highlighted word String. you might want to label each curve. If typing “\betaf(x)” sets your teeth on edge. Note: For you TeXers note the funny control sequence “\betaf(x)” which generates βf (x). 4. p1 + c2*cos(x). If more than one curve appears on a plot. and 3 = right) or which key (its ASCII representation) was pressed.”. This can be done directly using the text or gtext command. The size of the point marker. If you would have typed “\beta f(x)” you would have obtained β f (x) because MATLAB preserves spaces.) The default is size = 0. 0 • LineWidth 0 . The results are similar. button] = ginput(n) The vector button contains integers specifying which mouse button (1 = left. y. It is often essential for the title to include important information about the plot (which would. Advanced Topic: Commands interval [0. to the appearance of the text from the TEX program (so do some experi- menting). is 1/3 this size.† Labels can also be added to a plot.ypt) in units of the current plot. use >> [x. p2 >> plot(x.. also. i. “ ” and “ ” are used ˆ 2 R αfor superscripts and subscripts. “. and you can draw a point which is approximately one pixel in diameter by letting size = 1. Finally. 100) >> c1 = 2 >> c2 = -3 >> p1 = 1 >> p2 = 3 >> y = c1*sin(x). The default is to put the center of the left-hand edge of the text at this point. ypt. . suppose you enter >> x = linspace(0. size – where size is the width of the line in points (where 1 point = 1/72 inch. Then you † On a Macintosh computer you probably do not have a center mouse button. 62 . size – where size is approximately the diameter of the marker. Most of the “common” TEX commands can be used. have to be written down “somewhere” and connected to this specific plot). to collect any number of points enter >> [x. the x-axis can be labelled α and the y-axis 0 f (x) dx by >> xlabel( 0 \alpha 2 0 ) ˆ >> ylabel( 0 \int 0 \pi\betaf(x) dx 0 ) ˆ To see the complete list of TEX commands. y] = ginput Each position is entered by pressing any mouse button or any key on the keyboard except for the carriage return (or enter) key. The entire legend is put into a box and it can be moved within the plot by using the left mouse button. a legend can be put on the plot by >> legend(<string1>. TEX commands can be used in these strings to modify the appearance of the text. to determine which mouse button or which key was entered. y) ˆ ˆ and you want to “play around” with the two coefficients to obtain the most “pleasing” plot. 2 = center. 1]. other- wise.

this isn’t a great example.. enter doc colorspec. This can be done by >> str = [num2str(c1). You can also clear all the figures by >> close all All the above MATLAB commands can be used for 3-D graphics except for gtext. . enter >> colormap To change the color map..3. yellow.) In addition. (Alright. and black in the table “Customizing Lines and Markers” at the beginning of this section. 0 (x) + 0 . simply to make the example easier to read. magenta. green. y. C) or >> surf(X. New plots will now appear in this figure. >> text(x. For example. the mesh and surf commands allow us to plot a surface in three dimensions where the colors on the surface represent its height. 0 ˆ *cos 0 . 0 *sin 0 . You can avoid this difficulty by clearing the figure using >> clf which clears the current figure. Occasionally. Advanced Topic: Commands probably should have the title include a definition of the function — and you should not have to modify the title by hand every time you change the coefficients. Y. these are called the RGB components of a color.. the second column green. In this way much more information can be generated and viewed on the computer terminal.) You can also put plots in a new graphics window by entering >> figure where the figures are numbered consecutively starting with one (and appear at the top of the window). white. red. and makes it the current target for graphics commands. i. suppose you divide a window into a 2×2 ar- ray of plotting regions and use subplot to put a plot into each region. C) Each graphics window has a separate color map associated with it. The text command is the same as described above except that the position of the text requires three coordinates. num2str(c2). z. where each element is a real number between 0 and 1 inclusive. 4. you only want to put plots into two of these four regions. enter >> colormap(<color map>) where <color map> can be an explicit n×3 matrix of the desired RGB components or it can be a string 63 . which is also defined at each mesh point. This creates a new window. by changing the command to >> mesh(X. For mesh or surf the value of F (or of C if there is a fourth argument) is linearly rescaled so its mini- mum value is 1 and its maximum value is n. There is now a permanent record of the function which generated the curve. we show the RGB components of cyan. This color map is simply an n×3 matrix. For example. num2str(p1). and the third column blue. The value input to this color map is the row rep- resenting the desired color. 0 (x) 0 ] >> title(str) ˆ where we use the text variable t. makes it visible. (Handle graphics is discussed in the next subsection. num2str(p2). You can clear a particular figure by clf(n) or clf(<handle>). In each row the first column gives the intensity of the color red. it is useful to clear a figure. you can clear the current figure by >> close or a particular figure by close(<handle>). blue. F.e. Y. Next. you then save the figure into a file. <string>) As we discussed in the previous subsection. Or enter >> figure(n) and the figure will have the specific number n. F. for further information. but it’s better than nothing. To see the current color map. The difficulty is that the other two regions will still contain the previous plots. You can “bounce” between graphics windows by entering >> figure(n) where n is the number of the graphics window you want to make current. We can add a rectangle which contains the correspondence between the color and the height of the surface by adding >> colorbar We can also let the colors represent a separate quantity C. rather than putting the string directly into title.

You want the more positive values to be redder and the more negative values to be greener and a zero value to be white. 2))./ . 4. you can enter >> fill(X. to white. To obtain a more interesting pattern replace the above fill command by >> colormap( 0 hsv 0 ). (1 1 1). For example. Of course. in this case the number of endpoints of each polygon must be the same. F. 1.95 0. % 5 F = f(X. MATLAB can also fill-in two-dimensional polygons using fill or three-dimensional polygons using fill3.5. % 4 [X. 2*pi. sin(t). % 7 C green = [color scale. n). 2 + y))) . Advanced Topic: Commands containing the name of an existing color map. Y] = meshgrid(x. ysquare.e. >> s = 0.5*sin(2*pi*(x. 2 + 1. (1 + abs(x) + abs(y)).. % 11 colormap(C) % 12 contourf(X. Y. % 9 C red = [ones(size(color scale)). 0 y 0 ) >> axis equal. Suppose you have an “interesting” function which takes on both positive and negative values. 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 1 0 1 0 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 Then enter >> fill3(X. Y. We include an example which shows in detail how to modify the colormap directly when using contourf to generate a filled contour plot. Z= .5 . % 10 C = [C green. 100). The array C green goes from green. 20) % 13 caxis([-1 1]) % 14 colorbar % 15 The “amusing” function is defined in line 2. ones(size(color scale)).05:1] 0 . color scale]. input the matrices 0 1 1 0 0 0 0 0 1 1 0 0 0 0 1 0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 1 0 0 1 X= . [100:10:130]) Rather than entering polygons sequentially in the argument list. xsquare. to 64 . Y). Y. For example. y).. i. % 3 y = x. to draw a red circle surrounding a yellow square.5*(sin(2*pi*(x . % 1 f = @(x. (1 0.95). >> fill(cos(t). 0 r 0 .3. enter >> t = linspace(0.. C red]. (0 1 0). % 8 color scale = flipud(color scale(2:end))... [1:6]) >> axis equal Change your orientation using view to see all six faces. color scale]. sin(t). to draw a cube with all the faces having a different solid color.e.5 .y) . >> fill(cos(t). The array C red then goes from almost white. The existing color maps can be found by typing >> doc graph3d A useful color map for outputting to laser printers is 0 gray 0 .e. ˆ ˆ ˆ % 2 x = linspace(-1. by padding if necessary.05. in steps of 0. Read the documentation on fill and fill3 for more details. ysquare. In this colormap all three components of each row have the same value so that the colors change gradually from black (RGB components [0 0 0]) through gray [.5]) to white [1 1 1]). xsquare.y. This is easily done by %%%%% script m-file: colormap example n = 101. [1:100]. Y= . >> ysquare = [-s -s s s] 0 . <color>) where each column of X and Y contain the endpoints of a different polygon. i. i. >> xsquare = [-s s s -s] 0 . % 6 color scale = [0:. color scale. Z.

(1 0 0).) Incidentally.e. Then the image is displayed using the new color map. a picture) which is represented by a matrix X ∈ Rm×n . The types of files which can be imported are: “bmp”. “pgm”.e. white.3 . the zero value of F has a value of (1. where map is the associated colormap for the image. The minimum value is scaled linearly to the first color in the colormap. This is corrected in line 14 where caxis changes the endpoints used in the col- ormap to a minimum of −1 and a maximum of +1.. The complete array C is calculated in line 11 and the colormap changed in line 12. f max − f min MATLAB can also plot a two-dimensional image (i. or “wxd”. f max]) the value f is first modified to lie in the interval [f min. i. Advanced Topic: Commands red. say cij .15. “cur”. In >> image(C) each element of C. 0. “jpeg”. “jpf”. f min]). i. “png”. j)th element of X specifies the color to use in the current color map.. 65 . i. min(F(:)) = −0.. 4. many grayscale or color images can be imported into MATLAB by >> X = imread(<filename>). to the maximum value of F. (The axis command forces the earth to be round. in line 15 we attach the color map to the plot so that we can determine the values in the contour plot. “pcx”. and the maximum value to the last color. >> axis image displays an image of the earth. “pps”.) (In the demonstration program. j)th rectilinear patch in the plot. i. 0. in fact. For example. “tiff”. the current colormap. The (i. thus a value of 0 corresponds to the middle row of C which is. which should have integer elements. They can be shown by image or imshow. f max]). or >> [X. imagesc is a similar command. They can be exported by imwrite.3.e.. “gif”.e.58.15). Note: There is a linear scaling between the value of F and the corresponding color in the color map C ∈ Rn. “pmb”. rather than elliptical. also in steps of 0. corresponds to this entry in the colormap.05. This color ap- pear in the (i.e. after clicking on “Visualization” double-click on “Image colormaps” to see the images which you can access in MATLAB and the existing color maps. “ras”. but with one important difference. >> colormap(map) The image command inputs the matrix X and the colormap map from clown. Then the row ic of C is calculated by (f mod − f min)(n − 1) ic = fix +1. “j2c”. respectively. Thus. “pnm”. Similarly. “j2k”. it is a R`×3 matrix. max(F(:)) = 0. “hdf”. the zero value of F does not cor- respond to white because the colors in the colormap change linearly from the minimum value of F.89. However.. “fts”. but the matrix A ∈ Rm×n . Finally. >> imagesc(C) first determines the minimum element m1 and the maximum element m2 in C. If cij < 1 or cij > `. “tif”. “jpg”. “jpx”.e. f max] by f mod = max([min([f. For caxis([f min. i.. “ico”. to display the color image of a clown enter >> load clown >> image(X). >> colormap(map).mat. this command treats them as if cij = 1 or cij = `. Incidentally. has a different meaning. The filled contour is calculated in line 13. and let it have ` colors. However. “fits”. >> load earth >> image(X). map] = imread(<filename>). They both use the same colormap.

Values outside this interval map to the closest endpoint. . There are many properties of the text that can be changed in the text command by >> text(xpt. <string>) Adds the text to the location given in the units of the current plot. 4. y. we have to be able to refer to a particular object to change its prop- erties. (Each handle is a unique floating-point number. clf Clear a figure (i.4. In the previous parts of this section we have mainly discussed “high-level” graphics commands which allow us to create useful and high quality graphical im- ages very easily. figure Creates a new graphics window and makes it the current target. 0 <Prop 2> 0 . ypt. Each object has properties and we customize an object by changing its properties. such as a subplot. In handle graphics we consider every component of a graphical image to be an object. 4. <Value 1>.) We will use a small number of examples to explain handle graphics. The legend can be moved by using the mouse. <color>) Fills one or more polygons with the color or colors specified by the vector or string <color>. a surface. <string>. we will only discuss a few of — what we consider to be — the more useful customizations. <string>) gtext(<string>) Places the text at the point given by the mouse. legend(<string 1>. fill3(x. a piece of text.. Of course.. <Value 2>. figure(n) makes the nth graphics window the current target. . .) Places a legend on the plot using the strings as labels for each type of line used. Advanced Topic: Text and Positioning ginput Obtains the current cursor position. imagesc Plots a two-dimensional matrix and scales the colors imread Import an image from a graphics file. . ) or >> h = text(xpt. 0 <Prop 2> 0 . delete everything in the figure) colorbar Adds a color bar showing the correspondence between the value and the color. 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. y. <string>). <Value 1>. >> set(h. imwrite Export an image to a graphics file. This subsection will be quite short because we do not want to get bogged down in this complicated subject. z. a line. <Value 2>. etc. ) where <Prop ?> is the name of one of the properties for the text object and <Value ?> is one of the 66 . y. text(x. 0 <Prop 1> 0 . and a handle is the unique identifier which refers to a particular object. . but at the cost of having to get much more involved in how graphical images are actually created. The low-level commands allow us to customize these graphical images. an axis. o text(x. This is a collection of low-level graphics commands which do the actual work of generating graphics. . 0 <Prop 1> 0 . . y. image Plots a two-dimensional matrix.e. ypt. colormap Determines the current color map or choose a new one. Advanced Topic: Handles and Properties Advanced Topic: Plots caxis([v min.. Advanced Topic: Handles and Properties In this subsection we briefly discuss handle graphics. z. imshow Display an image. <color>) Fills one or more 3D polygons with the color or colors specified by the vector or string <color>. fill(x. demo Runs demonstrations of many of the capabilities of MATLAB.4. Instead.

and green components. >> plot(x. 0 on 0 ) >> set(gca. You can also change the default properties for gtext.exp(sin(x))) >> set(gca.4. 0 FontName 0 ) and the string s now contains the name of the font. zlabel. 16. and title. (We show some names and values in the following table. ylabel. suppose we want to plot the function y = esin x for x ∈ [0. or a string of the predefined colors.) FontSize The font point size.5 inches wide and 5. 0 1. red text which is rotated 90◦ . When we want to use the full size of a sheet of paper we use 67 . the fifth line adds small tick marks between the labelled ticks. 0 . xlabel. 0 TickDir 0 . baseline — The baseline of the text is placed at the point. { 0 0 0 . Advanced Topic: Handles and Properties allowed values.5*pi 0 . center — (default) The text is centered vertically at the point. (The default is Helvetica. In the latter the text command creates an object.5 inches high. using its default properties. (At present.) There is one case where we frequently use handle graphics. entering >> set(h. Text Properties Clipping on — (default) Any portion of the text that extends outside the axes rect- angle is clipped off — No clipping is done. The property value is the angle in degrees. blue. right — Text is right justified. In the former all the properties are set in the text command. 0 XMinorTick 0 .) HorizontalAlignment left — (default) Text is left-justified center — Text is centered. 0 XTickLabel 0 .5*pi 0 . 0 Rotation 0 . bottom — The bottom of the text rectangle is placed at the point. 0 Color 0 . For example. 0 out 0 ) where the third line puts major tick marks at multiples of π/2. VerticalAlignment top — The top of the text rectangle is at the point. The more common way of customizing parameters is by using the set command. The default size is approximately 6. 0 r 0 . There are two other commands 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. Rotation The text orientation. and the last line puts the tick marks outside the plot boxed area. The two functions get and set are used to obtain the value of one parameter and to set one or more parameters.101). The set command then changes some of the properties of the object whose handle is h. (The default is 10 point.2*pi. 0 FontSize 0 . 0 XTick 0 . the graphical im- ages do not fill the entire page. For a simple example which uses handle graphics. cap — The top of a capital letter is at the point. 0 pi 0 . We do this by >> x = linspace(0. we cannot use TEXcommands in XTickLabel to generate a Greek π. When a figure is printed. FontName The name of the font to use. For ex- ample. 90) results in a large. The two arguments to get are the handle of the object desired and the name of the property. 0 2*pi 0 }) >> set(gca. 2π] and we want the horizontal axis to have major tick marks at every π/2 and we want these tick marks labelled.) We have shown two ways to cus- tomize the properties. Color A three-element vector specifying a color in terms of its red. [0:pi/2:2*pi]) >> set(gca. to get the font which is presenting being used enter >> s = get(h. with handle h. 4. the fourth line puts the labels shown at each tick mark.

It usually consists of three elements: (1) Components: These are the tools which enable the user to interact with a program. show results of the program. not just in each subplot. Such an interaction is called an event. 0 <Prop 1> 0 . Of course. They also contain primary functions.e. and toggle but- tons. [0 0 1 0. Thus. >> title handle = get(axes handle. 4.1.5 11]) since the default units for this property are inches. pop-up menus. 0 on 0 ).. Note: Case is unimportant for property names. . the programmer must make the deci- sion whether or not to spend the time required to write a good GUI. typing) in the workspace. 0 PositionPaper 0 .95]. Note: <Value 1>. listboxes. The simple way to write a GUI is to type >> guide This launches a GUI which you can use to write your own GUI. 0 Visible 0 . In this subsection we are only concerned with how to write a GUI — not how to write a good one. MATLAB makes it very easy to create a graphical user interface for a program. For exam- ple. Set the property. set(<handle>. gca The current axes handle. The second line gets the handle for the title object of the new axes. and include push bottoms. editable text. The largest part of this window is a rect- angular and gridded canvas into which the various components are placed. 0 off 0 ). Note that this not only includes the time required to code the GUI but also the — possibly much longer — time required to design the GUI. 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). of the object with this handle. Advanced Topic: Properties get(<handle>.5. The axes are invisible because they are only being created so that a title can go on top. subfunctions.. Advanced Topic: GUIs (Graphical User Interfaces) >> figure( 0 PositionPaper 0 . However. this is often not easier for the users. Finally. <title>. or properties.5 11]) or >> figure(n) >> set(gcf. This can be done by >> axes handle = axes( 0 Position 0 . [0 0 8.5. A GUI is a graphical display which allows a user to interact “pictorally” with a program. 4. 0 Visible 0 . but it is not directly connected with the program. if subplot is being used. To the left of this canvas is a 68 . radio buttons. This is frequently useful if subplot is being used to put a number of plots on a page. 0 <Prop> 0 ) Return the current value of the property of the object with this handle. (3) Callbacks: These are pieces of code which enable the user to interact with the program. it is sometimes useful to put a title on the entire page. Advanced Topic: GUIs (Graphical User Interfaces) Warning: The codes in this subsection use for loops and if tests which are discussed in Section 8. it is usually even easier for the programmer to have the users interact with a program by entering data (i. gcf The current figure handle. this triggers an event. Components can also include plots and/or tables which allow the program to interact with the user.e. which is a graphical window which is separate from the MATLAB window which arises when MATLAB is first executed. and a program which responds to events is event driven. 0 String 0 . (2) Figures: All of these components must be arranged within a figure. The third line puts <title> into the title object and makes it visible. when a user uses a mouse to click a button.3. sliders. 0 Title 0 ). and nested functions which are discussed in Section 8. [0 0 8.) Case is unimportant for property names. >> set(title handle.. 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. check boxes.. It is the responsibility of the programmer to write the code which specifies how how each event affects the program. i.

60]) xlabel( 0 x 0 ) ylabel( 0 y 0 ) zlabel( 0 z 0 ) title(t) drawnow end which generates the “interesting” surface z = f (x. the fig file (i. ˆ view([-45. and we will not discuss how to integrate your program and code the callbacks. the components.2η(y)]η 2 (y) where η(y) = y + 0. Since this can get quite compli- cated.. Z = sin((at + . the extension is fig) and the function file (i. Instead. For the first example consider the function function rippling(a. bt = b + . Read this documentation carefully and work through this explicit example yourself. are your responsibility. we will show how to take a simple figure which is created by the plot command and add “something” to it. t.e..4t)[sin 2η(y) + 0. It is “rippling” in time (and the time is shown at the top of the 3D surface). Yxy = Y + . 2.8*t. we only show two very simple examples. 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. the extension is m). When done. surf(X.. you save your GUI under its own name. b) n = 101. You build your own GUI by positioning any or all of these components in the canvas. and the callbacks. 2 + .1x + 0.2η(y)]x2 + (b + 0. You have created two files.e..*X. What we will discuss is how to use the non-simple way to write a GUI. y = x. ˆ bt*(sin(2*Yxy) + . but only a very small subset. [X. 2).8t) + 0. The third part.5. i.* Yxy. Suppose we would like to stop the time evolution briefly to admire the surface. Thus. Y.e.25*sin(2*(exp(X/2)-1)). Z). 4. a.25 sin 2(ex/2 − 1) . b) = sin [(a + 0. This is easily done by 69 . for t = 0:.1*X + . including an explicit example which is called simple gui. we will not attempt to describe all the commands which are involved in generating a GUI. y. y). We will not discuss guide any further. x = linspace(-2. This is well-documented in MATLAB.. Y] = meshgrid(x. either using icons or their actual names.01:10 at = a + .2*Yxy). So far you have only created the first two elements of a GUI: the components and the fig- ure. n). namely by writing all the actual commands which setup the figure. Advanced Topic: GUIs (Graphical User Interfaces) list of all the possible components.2*Yxy). the callbacks.4*t. We will not write any GUIs from scratch.

The next line in the code runs the function rippling (which has been discussed previously) using the parameters a = b = 0.. The last pair of argu- ments makes the event of pushing a button execute the function button. and the fourth the position of the button in the figure (using these units). or static text field) in the figure. the third that the units are pixels. However. (uipanel can be used to split the GUI into different regions. or creates a new figure. radio button. push button. . 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.. The uicontrol command (user interface control) positions a component (check box. the second that the word Pause should appear on the button. . 0 String 0 . As long as the user does not click the push button... The following set command changes the label on the push button back to Pause.. event) str = get(hObject. [0 0 80 20]... the push button still does not do anything. 0 String 0 . . The following one does. 0 Style 0 . 70 . (The second argument is unused. uiwait then blocks execution of the program (i. 0 Pixels 0 . uiresume is executed so the program resumes execution. button is again executed and now the if statement is false because str contains Continue. in a two-dimensional plot this is a “safe” location. The first pair of arguments makes this control a push button. everything is as if rippling was run directly from the workspace. † 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. which is called its parent.. 0 Pause 0 .† However. slider. 0 Pause 0 ) set(hObject. a uicontrol can then be attached to any of these panels or the original figure.. 0) % the above function which generates the surface %%%%% subfunction function button(hObject.e. This component must be attached to something. 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. The command set is executed and it re- places the push button label by Continue. The discussion of this code follows.. . This value is the string Pause and so the if statement is true. 0 String 0 . ).) get returns the value of the property name String which is attached to the handle hObject. 0 Pause 0 ) end The actual figure is shown below when the push button has been clicked. (It is not actually needed because the default parent is the current figure. toggle buttons. rippling(0. .. Advanced Topic: GUIs (Graphical User Interfaces) function pause rippling shg uicontrol(gcf.) 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 . plotting the surface). pop-up menu. 0 Position 0 . 0 Units 0 .. . 0 PushButton 0 . @button). 0 Continue 0 ) uiwait else uiresume set(hObject. if strcmp(str. 4. triggering an event) causes the function button to be ex- ecuted where the first argument hObject is a handle to the particular event. 0 Callback 0 . Clicking the push button (i. editable text field. list box. The above GUI does not allow us to modify a or b.) The first argument to the uicontrol command in the code determines its parent. shg either raises the current already-existing figure. but it never hurts.5. .e. 0 String 0 ).

5. Advanced Topic: GUIs (Graphical User Interfaces) 71 . 4.

4. 0 Style 0 . 0 Edit 0 . @edit a). . . 0 String 0 . 0 Units 0 . Note that the value of a is contained in the String property name and its string value is num2str(a. 0 Position 0 . uicontrol(gcf.† If the number (actually the string) is modified. .. 0 Style 0 . 0 Position 0 .e.5. 0 a = 0 . uiwait. [220 0 60 20]. 0 Text 0 . 0 Style 0 .. 0 b = 0 . a = 0. event) a = str2num(get(hObject. ‡ The function button is also a nested function. Note that this is a nested function (to be discussed in Section 8. 0 String 0 ). num2str(a. @edit b).. 0 Start 0 ) uiresume set(hObject. it can be either. 0 Start 0 . drawnow uiwait rippling(a. 0 %4.. 0 PushButton 0 . 0 %4.2f 0 )... 0 Position 0 . 0 Callback 0 . 0 Pause 0 ) end end function edit a(hObject. in this function the value of a is changed by getting the character variable and changing it to a number. 0 Callback 0 .3) so that the value of a which is modified in this function is also modified in the primary func- tion pause rippling2. Since it does not modify a variable which is needed by the primary function. 0 String 0 )).. b = 0. 0 String 0 . which causes the function button‡ to be executed. 0 Pixels 0 . Advanced Topic: GUIs (Graphical User Interfaces) function pause rippling2 shg h pause = uicontrol(gcf. uicontrol(gcf. 0 Pause 0 ) elseif strcmp(str. 0 Callback 0 . [190 0 30 20]). event) b = str2num(get(hObject. b) %%%%% nested functions follow function button(hObject. uicontrol(gcf. . The function rippling does not begin running until it is pushed. if strcmp(str. puts the GUI into a wait state. i. 0 Edit 0 . The next two uicontrol s put in the static text field “a =” and the editable text field which contains the default value of a. 0 Pause 0 ) set(hObject.2f 0 ). This state continues until the user clicks the push button. end end This is shown below where both a and b have been modified and the push button has been clicked. 0 Position 0 . 0 Style 0 . [90 0 30 20]). whereas it was a subfunction in pause rippling.. 0 Position 0 . The first uicontrol is the same as before. except that the word Start initially appears on the push button. 0 String 0 . @button). 0 Text 0 . The string contains Start so the if statement is true so the GUI resumes execu- † The second argument to num2str causes the number to appear as ± × . 0 %4. The last two uicontrol s do the same for b. 0 Continue 0 ) uiwait else uiresume set(hObject. [0 0 80 20]. Since edit a and edit b need to 72 . is necessary so that the components actually appear in the figure. [120 0 60 20]. end function edit b(hObject. 0 Style 0 . 0 String 0 . which immediately follows the creation of all the components. 0 String 0 )). event) str = get(hObject. num2str(a. The following command. the function edit a is executed. 0 String 0 . 0 String 0 .2f 0 ). 0 String 0 . uicontrol(gcf. the label alter- nates between Pause and Continue. Afterwards. The drawnow command. 0 String 0 . × ×..

Advanced Topic: GUIs (Graphical User Interfaces) tion. we also made button one. 4. be nested function.. i. 73 . the function rippling is executed.e. and the label is changed to Pause.5.

6. but only used by some components). an external software package must then be used to combine these files into a movie. ”Life” is a cellular automaton invented by John Conway that involves live and dead cells in a rectangular.) nents are: check boxes.1 $ $Date: 2004/08/16 01:38:30 $ This code strips out the part of life which does the actual iterations and shows how to save the re- sults in an avi movie. the calculations required become astonishingly simple. SliderStep (only used by some components). 4. We use periodic (torus) boundary conditions at the edges of the universe. Another disadvantage of the first and third methods in Linux and Mac is that the movie file which is generated is not compressed. Whether cells stay alive. Adapted by Ned Gulley. die. Position. 6-21-93 Copyright 1984-2004 The MathWorks. A third method. 4. or generate new cells depends upon how many of their eight possible neighbors are alive.. Advanced Topic: Making Movies GUI guide Invoke the GUI design environment to design your own GUI. static text labels. editable text fields. 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. Advanced Topic: Making Movies There are a number of different ways to make movies in MATLAB. the disadvantage is that each frame must be individually saved to disk.. Note: Case is unimportant for property names. Style (which component). Some of the proper- ties are: BackgroundColor. UserData (user spec- ified data). toggle buttons. LIFE MATLAB’s version of Conway’s Game of Life. . In MATLAB.10. Create a user interface component. Max (maximum value.. and Visible (whether the component should be currently visible). radio buttons. uiwait Block execution of the GUI. An external software package 74 . . two-dimensional universe. $Revision: 5. This is used to subdivide the <Value 1>. but only used by some components). uipanel(<handle>.4.) GUI if desired. The first argument (which is optional) is the handle of the parent (default is gcf). Callback. C. uiresume Resume execution of the GUI. Inc). is then discussed. sliders. 7-11-92. FontUnits. the universe is a sparse matrix that is initially all zero.6. 8-7-92. Pressing the ”Start” button automatically seeds this universe with several small random communities. The advantage of the second method is that no additional memory is required. String. ForegroundColor. Inc. The documentation inside life follows.. 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. Two different methods are shown explicitly in the code. 0 <Prop 1> 0 . list boxes. FontSize. but only used by some components). Create a user interface panel. Value (current value of component. Units. and then closes it. Parent (instead of using the first argu- ment). Moler. adds frames explicitly to the movie. The second only saves each frame in a jpg file. Min (minimum value. The various compo- <Value 1>. By using sparse matrices. pop-up menus push buttons. The first initializes the movie. 0 <Prop 1> 0 . Some will succeed and some will fail. uicontrol(<handle>. which is a slight modification of the first.

% 13 figure(gcf).:) + X(:. and logical expressions.w) + X(n. F). % 30 [i. % 3 m = 26. % 16 title([ 0 # iter = 0 . % 26 w = [m 1:m-1]. num2str(nr iter)]) % 34 drawnow % 35 F = getframe(gcf). % 23 n = [m 1:m-1].4)*rand(1)) + 2.ky+p) = (rand(3) > 0. 0 %06d 0 ). m).jpg 0 ]. 0 xdata 0 . % 15 plothandle = plot(i. % 39 if X == Xprev2 % 40 break % 41 else % 42 Xprev2 = Xprev. 0 . iseed). % 27 while true % 28 N = X(n.:) + X(s. file name).) 75 . % 2 M = avifile( 0 life movie. i. % 17 drawnow % 18 F = getframe(gcf). Advanced Topic: Making Movies must be used to compress it. j] = find(X).w) + . % 22 Xprev2 = X.e) + X(s. % 9 ky = floor((m .. % 29 X = (X & (N == 2)) | (N == 3). %%%%% script m-file: sample movie % modified from the MATLAB function life which is % Copyright 1984-2004 The MathWorks. % 31 nr iter = nr iter + 1. 0 . 4.5).. num2str(nr iter. while. % 14 nr iter = 0. % modify seed to obtain different cells % 1 rand( 0 state 0 . j. find. % 7 for count = 1:15 % 8 kx = floor((m . break. Inc. % 25 s = [2:m 1]. for. % 20 file name = [ 0 life movie 0 . num2str(nr iter)]) % 16 axis([0 m+1 0 m+1]). % 37 file name = [ 0 life movie 0 . j) % 33 title([ 0 # iter = 0 . Warning: This code uses a number of MATLAB commands which have not been yet discussed: sparse. 0 Red 0 . iseed = 3343. % 51 (This m-file is contained in the accompanying zip file. if.4)*rand(1)) + 2. 12). num2str(nr iter. % 5 X = sparse(m. % 10 X(kx+p. 0 MarkerSize 0 .avi 0 ). % 4 max nr iter = 10000. % 21 Xprev = X. % 32 set(plothandle.MAXIMUM NUMBER OF ITERATIONS EXCEEDED 0 ) % 47 break % 48 end % 49 end % 50 M = close(M). % 19 M = addframe(M.6. % 36 M = addframe(M. % 24 e = [2:m 1].w). 0 . % 12 [i.e) + X(:. 0 Color 0 . file name). X(s. % 11 end. 0 .j] = find(X). % 38 saveas(gcf. 0 %06d 0 ). 0 ydata 0 . % 43 Xprev = X. % 22 saveas(gcf. % 44 end % 45 if nr iter > max nr iter % 46 disp( 0 EXIT .jpg 0 ].e) + X(n. F). % 6 p = -1:1.

There is another slightly different way to make a movie. Lines 20 and 38 are modified to F(nr iter+1) = getframe(gcf). 4: The size of the grid is m × m. 53: Creates a movie directly. (You can even supply your own. its color. (This “low-level” command generates a new plot much faster than using the plot command directly but. this makes it visible both as a figure and on the computer screen. 38–39. 37: Updates the current figure since if a number of plots are drawn in immediate succession only the last is made visible. 0 life movie. Lines 3. the plot command is “fast enough”. the second cap- tures the first frame and the third appends it to the object M. The last line is necessary for clearing the buffers and closing the file life movie. 6: Creates a m × m sparse matrix with all zero elements. 20–21.6. 38–39. and makes it visible.avi. 35–37: Plots the next iterate using the set command rather than the plot command. See the parameter name com- pression in the documentation and try the various codecs to see which is “best”. After this MATLAB function has ended. all these jpg files can be combined into a movie using various software pack- ages. Note: Lines 3. and the size of the dots. 5. 48–51: The maximum number of iterations is needed since with certain initial conditions the game will never end. you can view this movie in MATLAB by using the movie command. and 39–41 are deleted. 14: If there is a current figure. Note: The movie is compressed by default in Microsoft Windows. 33: Determines the nonzero elements of X. puts a title on it. 31–32: Generates the next iteration. 4. 21–23. This is then repeated for every iteration. If they are identical. almost always. 1–2: Initializes a “reasonably short” iteration sequence on my computer of 52 iterations — but this is not necessarily true on yours. and line 53 is modified to movie2avi(F. 16–18: Plots the initial configuration. 52: Calculates and plots each successive iteration. Advanced Topic: Making Movies A discussion of this code follows using the line numbers. puts a title on it. (Modify the seed if necessary on your computer. 20–21. It is immediately saved to disk. the iterations have settled down and the run ends. 76 .) 42–47: Compares the current and the second previous iteration. 13. The plot is given the handle plothandle. 45–46: Saves the previous iterate and its previous iterate in order to determine if the game has settled down. 15. 22–23. 30. Incidentally. 24–25. 40–41: Shows an indirect way to make a movie. 19. and sets the limits on the axes.) 7–12: Calculates the initial configuration. The first line initializes the object M. (See Section 9.) 3. and 54 are not needed. SAY MORE??? Note: The second argument in num2str is essential so that the files appear in the correct order in the directory. Each frame is given a name with a unique number identifying the iteration number. 26–29: Initializes the variables needed to update the iterates. Note: Lines 22–23 and 40–41 are not needed to create the movie using this method.) Warning: The movie cannot exceed 2GB.avi 0 ) This movie is also compressed in Microsoft Windows. 34: The current iteration number.

These two plots should fill an entire sheet of paper. (a) Begin by plotting ex for x ∈ [−1. (a) Plot this function for x. (e) The above plot is not very instructive because ex − p3 (x) is much smaller than either ex or p3 (x)... use two plots. 5. . aj1 x1 + aj2 x2 + · · · + ajn xn = bj . . saveas Save a figure to disk. ex − p3 (x) on the same graph. What does the surface look like if you don’t? (b) This surface has high peaks which interfere with your view of the surface. Consider the function f (x. . Solving Linear Systems of Equations Movies avifile Create a new avi file. addframe Add a frame to the avi file.∗” operator in front of each sine term. Explain how the local function running gaussians works. explain how the sum of all the modes is calculated in the function g. Plot ex and one of its Taylor series approximations. . (d) Next. . am1 x1 + am2 x2 + · · · + amn xn = bm . which is immediately below the first.. Solving Linear Systems of Equations One of the basic uses of MATLAB is to solve the linear system a11 x1 + a12 x2 + · · · + a1n xn = b1 a21 x1 + a22 x2 + · · · + a2n xn = b2 . Note: There are an infinite number of answers to this part.e. 5. movie2avi Save the current movie frames to an avi file. The solutions are given on page 163. Instead. Change your viewpoint so you are looking down at the surface at such an angle that the peaks do not block your view of the central valley. (c) Also plot the difference between ex and this cubic polynomial. 2. i. movie Play movie frames. Be Able To Do After reading this section you should be able to do the following exercises. contains ex − p3 (x). force the axes to be to the same scale.. +1].. . Put labels on the x and y axes and a silly title on the entire plot. Note: Make sure you use the “ . getframe Get the current frame. +2]. y ∈ [−2. close (<avifile>) Close the file opened with avifile. 1. (b) Then plot x x2 x3 p3 (x) = 1 + + + 1! 2! 3! on the same graph. The first plot contains ex and p3 (x) and the second plot. In particular. 77 . y) = (x2 + 4y 2 ) sin(2πx) sin(2πy) . 4. generate a new graph containing all three curves by using only one plot command. and let all three curves have different colors. 3.7.

.) If A has one (or more) of these properties. UT – the matrix is upper triangular. one solution. We can also solve it by >> x = linsolve(A.. then kj+1 > kj . the second column is the coefficients of the x2 term. and the last column is the coefficients on the right-hand side. i. That is. Normally. .e... The appropriate MATLAB function is now rref..1. The vertical line between the last two columns repre- sents the equal sign..??? = false (We discuss logical variables in Section 8.. Normally. For our purposes the most important proper- ties are lower triangular. Square Linear Systems or the equivalent matrix equation Ax = b . . prop) where prop is a logical structure with the following elements: LT – the matrix is lower triangular. .. if the first nonzero term in the j th equation is xkj and in the (j+1)st equation is xkj+1 . • The first nonzero term in a particular linear equation occurs later than in any previous equation. Enter >> x = linspace(A. a2n b2 . SYM – the matrix is symmetric triangular. an augmented matrix is written without explicitly writing the header information. a1n b1 a 21 a22 . Square Linear Systems As we discussed previously.??? = true where ??? is one of the above properties..3. 5. upper triangular. etc. It is simply a linear system of equations written in shorthand: the first column is the coefficients of the x1 term.1. . symmetric. . all the elements are false.. To turn this property back off. it continues until it has zeroed out all the elements it can. b.. however. amn bm Warning: It is very important to realize that an augmented matrix is not a matrix (because the operations we apply to augmented matrices are not the operations we apply to matrices).. . am1 am2 . The third argument to linsolve gives the particular property. To use rref.1. set the property you want to true by >> prop. and positive definite. the linear system must be written in augmented matrix form. 5. . it doesn’t stop there. and POSDEF – the matrix is positive definite. We will discuss the case where m 6= n in detail in Section 5. However. in which case it has no nonzero coefficient). enter >> prop. the vertical line representing the equal sign should be included to explicitly indicate that this is an augmented matrix.. Note that there are m equations in n unknowns so that there may be zero solutions to this linear sys- tem. when m = n the MATLAB operation >> x = A\b calculates the unique solution x by Gaussian elimination when A is nonsingular. . 78 .. When A is singular there are either zero solutions or an infinite number of solutions to this equation and a different approach is needed. b) The advantage of using linsolve is that it can be much faster when A has a particular property. When done. It begins by ap- plying Gaussian elimination to the linear system of equations. Here we concentrate on m = n. x1 x2 ··· xn = rhs a11 a12 . . or an infinite number of solutions. 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. it can be solved much faster than using x = A\b. both above the main diagonal as well as below it.

The augmented matrix for this linear system is 1 2 3 −1 4 5 6 −1 . 5.1. 7 8 9 −1 Since A is a singular matrix. 7 8 10 0 (We have included the header information for the last time. consider the system of equations x1 + 2x2 + 3x3 = −1 4x1 + 5x2 + 6x3 = −1 7x1 + 8x2 + 10x3 = 0 . the solution of the linear system is x1 = 2.) Entering >> rref([A b]) returns the augmented matrix 1 0 0 2 0 1 0 −3 . when written back out as a linear system of equations. but only on linear systems of equations. Square Linear Systems 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. 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 . 0 0 1 1 Clearly. the linear system has either no solutions or an infinite number of solutions. For example. Of course. This is equivalent to the matrix equation Ax = b where 1 2 3 −1 A = 4 5 6 and b = −1 . The result is an augmented matrix which. 0 0 0 0 79 . is particularly easy to solve. which is equivalent to the matrix equation Ax = b where 1 2 3 −1 A = 4 5 6 and b = −1 . 7 8 9 0 Entering >> rref([A b]) returns the augmented matrix 1 0 −1 1 0 1 2 −1 . 7 8 10 0 The augmented matrix for this linear system is x1 x2 x3 = rhs 1 2 3 −1 4 5 6 −1 . x2 = −3. and x3 = 1.

b = 1. if you enter >> C = [0. 0. if 0.. It uses the variable tol to determine whether an element of the augmented matrix 0. the solution is x1 1 + x3 1 x3 1 1 x2 = −1 − 2x3 = −1 + −2x3 = −1 + x3 −2 .95 0.97 then the matrix I − C is singular (where I is the identity matrix).03 C= 0. However.† Solving Linear Systems linsolve(A. [0 0] 0 ]) MATLAB displays ans = 1 0 0 0 1 0 which indicates that the only solution is x = 0.03. Warning: The command rref does not always give correct results. the determination whether a number “should” be set to 0 depends on the magnitude of the elements of b. 80 .95 0.03 b2 is “small enough” that it should be set to 0.97]. look at the actual coding of rref. The maximum of the number of rows and columns of the augmented matrix. b. † To understand this “switch”. Clearly there is some value of b between 0 and 1 where MATLAB switches between believing that I − C is non-singular and singular.. inf).05 −0. if you solve (I − C)x = 0 by >> C = [0.)). −1.97]. max(size(. eps) which decreases the tolerance to eps.95 0.05 0. 0 0 0 1 Since the third equation is 0 = 1.) Since b is the last column of the augmented matrix. x3 x3 0 x3 0 1 Suppose you modify the matrix equation slightly by letting b = (−1. Now entering >> rref([A b]) results in the augmented matrix 1 0 −1 1 0 1 2 −1 . 0. You can obtain the correct answer to the homogeneous equation by entering >> rref([eye(size(C))-C [0 0] 0 ]. On the other hand.e. In vector form. the “size” of this matrix depends on the size of the elements of b. Thus.05 0.03. is multiplied by eps and this is multiplied by the “size” of the augmented matrix. rref Calculates the reduced row echelon form of a matrix or an aug- mented matrix. >> rref([eye(size(C))-C [b 0] 0 ]) then MATLAB realizes that I − C is singular. 5. ( norm in Section 7.05 0. i. For example. <properties>) Solve the linear system of equations Ax = b where A has certain properties.1. tol is (essentially) calculated by tol = max(size(<augmented matrix>)) * eps * norm(<augmented matrix>. there is clearly no solution to the linear system. Square Linear Systems so the solution of the linear system is x1 = 1 + x3 and x2 = −1 − 2x3 for any x3 ∈ R (or C if desired).05 0.03 b1 −0. 0)T .. >> rref([eye(size(C))-C.

. 1/n 1/(n + 1) 1/(n + 2) . the errors that have resulted have been very small. . . . note that MATLAB is warning you that it thinks something is wrong with the statement Warning: Matrix is close to singular or badly scaled. . 7 8 9+ep]. 1 1/2 1/3 . inv(A)*A . even though all the calculations have been done to approx- imately 16 significant digits.) Now choose some small nonzero values for and see what happens. the result is only accurate to three to . about this matrix. or divide cor- rectly! Up until now. (Recall that H (1/2) is very different from H. i. ( H (1/2) ) 2 . . The next example is more interesting. the reason for the large errors is easy to understand. suppose you solve the matrix equation Hx = b for a given b. multiply. but. .e. or strange. .xnum The result is not very satisfactory: the maximum difference in the elements of the two vectors is usually somewhere between 10−5 and 10−3 . Catastrophic Round-Off Errors 5.H ˆ ˆ the result is not particularly surprising. Now we present two examples where the errors are very large.. 1). Other possible names are epsi or epsilon. However. x = rand(n. every element is in magnitude less than 10−15 . xnum = H\b and compare x with xnum by calculating their difference. . . If you type >> n = 10. . RCOND = 1. subtract. after all. i. because of round-off errors. . . b = H*x. How small can be before MAT- LAB warns you that the matrix is “close to singular or badly scaled”? In this example. consider the Hilbert matrix of order n. . 4 5 6. . 1/(n + 1) 1/3 1/4 1/5 . 1/n 1/2 1/3 1/4 .2.e.) The ˆ ˆ resulting matrix should be the zero matrix. Consider the matrix 1 2 3 A = 4 5 6 .. However. 5. . Catastrophic Round-Off Errors We have mentioned repeatedly that computers cannot add. H = hilb(n). 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. it is not. ( RCOND is its estimate of the inverse of the condition number. 1/(n + 2) Hn = . .. For the second example. But how well does MATLAB do when 1? Enter >> ep = input( 0 ep = 0 ). In this first example. >> x .) Begin by letting = 0 and observe that the result displayed is nowhere close to the zero matrix! However.2.. . (Do not use eps for the name of this variable or you will change the predefined variable eps. . Then solve Hx = b for x and compare the final and initial values of x. (1/2). That is. Results may be inaccurate. A = [1 2 3. . hij = 1/(i + j − 1) so the elements are all of “reasonable” size. See cond in Section 7 for more details. How close is the numerical solution to the exact solution? Of course. so everything looks fine. Do this in MATLAB by >> n = 10.eye(size(A)) so that the final matrix should be O. 1/(2n − 1) which is generated in MATLAB by >> H = hilb(n) There does not seem to be anything particularly interesting.541976e-18. 7 8 9+ which is singular when = 0 and nonsingular otherwise. you know that the matrix is “close to singular” if is small (but nonzero) even if MATLAB does not..

ve significant digits! (To see how 81 .

3.e. enter >> n = 1000. instead. x = rand(n. 29/60 )T (after using the MATLAB command rats which we discuss below). you can find a “best” approximation by finding the solution for which the vector r = Ax − b which is called the residual. For example. MATLAB warns you of this fact and then returns one of the solutions. In general. If you enter >> A\b the response is Warning: Rank deficient. It is not that solving a matrix equation necessarily introduces lots of round-off errors. However. b = R*x. Overdetermined and Underdetermined Linear Systems If A ∈ Cm×n where m > n. (If A is complex. 5. This best approximation is calculated in MATLAB by typing >> A\b Analytically. On the other hand. Note that this is the same command used to find the solution to a square linear system.xnum)) The results are much more reassuring. that is.3. it is easy to repeat this experiment many times for differ- ent random numbers by simply rerunning this one line. n X 1/2 norm(r) ≡ ri2 i=1 is minimized. if there are an infinite number of least-squares approximations.000 times as many floating point operations needed to calculate x by Gaussian elimination for this random matrix! Note: By entering all the commands on one line. If there are an infinite number of least-squares solutions. For example. which is denoted by A+ . It also returns the solution (−1/4 .) It is important to realize that most calculations in MATLAB are very accurate. MATLAB interprets this command as asking for the least-squares solution. also called the Moore-Penrose pseudoinverse. 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. 5. This can be calculated us- ing the pseudoinverse of A.) This is called the least-squares solution. Instead. This cannot be the intent here since A is not a square matrix. 0. solve AH Ax = AH b.8 and 7. you find that the results are quite accurate. Ax = b is called an overdetermined system because there are more equa- tions than unknowns. repeat the above commands for n = 12. there are no solutions to this linear equation. the pseudoinverse is the unique n×m matrix which satisfies the Moore-Penrose conditions: • AA+ A = A 82 . even though n is 100 times as large for this random matrix as for the Hilbert matrix — and even though there are over 600. However.4594e-14. the approximation can be calculated by solving AT Ax = AT b . Again. max(abs(x . the solution desired is the “smallest” one. Hilbert matrices are very “un- stable” matrices — working with them can lead to inaccurate results. However. i. if you repeat the above sequence of steps with a random matrix. the x for which the length of the vector x is minimized. For example. 1). most matrices are quite “stable”. Since A is not square. it cannot have an inverse. (The norm function is discussed in Sections 2. xnum = R\b. Overdetermined and Underdetermined Linear Systems much worse the result can be.) Occasionally. this command only makes sense if there is a unique solution which mini- mizes the length of the vector Ax − b. rank = 2 tol = 1. is smallest in Euclidean length. which is one particular least-squares approximation. R = rand(n).. numerically this is less accurate than the method used in MATLAB. but has an infinite number of least-square approximations.

when it is an underdetermined solution. 7/90. m > n where A ∈ Cm×n . Solving Linear Systems A\b When Ax = b is an overdetermined system. entering >> rats(1/3 . allow much finer control over input and output. there are an infinite number of solutions to this equation. File Input-Output • A+ AA+ = A+ • (AA+ )T = AA+ • (A+ A)T = A+ A In particular. this is the least-squares approximation. If all the elements of A and b are rational num- bers. <permission string>) where the file identifier fid is a unique nonnegative integer attached to the file. suppose that A ∈ Cm×n with m < n. which behave very similarly to their C counterparts. 4/9)T . (Three file identifiers al- ways exist as in C: 0 is the standard input. this is a solution which has 0 in many of its elements. (In the previous example it is (−13/45.1/17 + 1/5) results in the text variable 121/255. 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). For example. File Input-Output In Section 4. although stored as a floating-point number. 1 is the standard output. rats(sqrt(2)) makes no sense (as was known to Pythagoras)..e. The MATLAB commands fscanf and fprintf. One command which is occasionally useful is rats. m < n. In general. This is frequently the exact value. 6.) Next. if A is a square nonsingular matrix. We can find one particular solution by entering >> A\b This solution will have many of its elements being 0. then A+ is precisely A−1 . rats(x) Calculates a “close” approximation to the floating-point number x. i. Ax = b is called an underdetermined system because there are less equations than unknowns.. It is also possible for an underdetermined system to have no solutions. then the solution and/or approximation obtained is usually a rational number. This command displays a “close” rational approximation to the floating-point number. Before using them a file has to be opened by >> fid = fopen( 0 <file name> 0 . this returns the one with the smallest length.) The permission string specifies how the file is to be accessed: 83 .1 we discussed the csvread and csvwrite commands which allow simple input from and output to a file. i.e. which is the correct answer. pinv(A) The pseudoinverse of A. and 2 is the standard error. 6. which may or may not be the exact answer. 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. Warning: Be careful when using this command.

to integer notation. Thus.360000e+01 Note: It is easy to print the matrix A in the MATLAB workspace as we just described. • An integer which specifies a minimum field width. 6.end To read formatted data from a file. −1 is returned in the file identifier. the file is created. These variables are printed out in order and matrices are converted to col- umn vectors (i.e. and.6 three different ways to display it are >> x >> disp([ 0 x = 0 . or is not used at all. and the two integers are separated by a period. If neces- sary. al- though it is actually a number of statements. <size>) The data is read from the file specified in a previous fopen command according to the format string and put into the matrix A. fprintf can also be used to format data on the screen by omitting the fid at the beginning of the argument list. The following works and can be entered on one line. 0 r+ 0 read from and write to the file (anything previously contained in the file is overwritten). if possible. <variable 2>.. To write formatted data to a file. which puts an upper limit on the amount of data to be read. c The argument is a single character. .. the output appears on the screen. it is possible to display a variable using as little or as much control as desired.. if x contains −23. 0 %s\n 0 .for i = [1:size(Str.6e\n 0 . num2str(x)]) >> fprintf( 0 %12. 0 w+ 0 read from and write to the file (anything previously contained in the file is overwritten). Str(i. the minimum field width is pre- ceded by an integer which specifies the maximum field width. File Input-Output 0 r0 read only from the file. If the fopen command fails. A → A(:) ). Enter >> fclose(fid) if a file needs to be closed.6000 -2. 84 . The format string is very similar to that of C. • If the maximum field width is larger than the minimum field width. If it is [m n]. 1)] fprintf(fid. <variable 1>. x) and the results are x = -23. the file is created. >> Str=num2str(A). If necessary. the conversion characters are: d The argument is converted to decimal notation. To briefly review some of the C format specifications. enter >> A = fscanf(fid. g The argument is a floating-point number in either “E” or decimal notation.6000 x = -23. 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.) The elements contained in the variables are written to the file specified in a previous fopen command according to the format string. <format string>. If it is a scalar. f The argument is a floating-point number in decimal notation. then A is a matrix of this size. A is actually a vector. e The argument is a floating-point number in “E” format. <format string>. For example. is optional. 0 0 a append to the end of the file (everything previously contained in the file is retained). If fid is omitted. it is a little more difficult to print it to a file. Each conversion character is preceded by “%”.:)). 0 w0 write only to the file (anything previously contained in the file is overwritten). enter >> fprintf(fid. The following may appear between the “%” and the con- version character: • A minus sign which specifies left adjustment rather than right adjustment. The size argument. However. s The argument is a string.

fclose(fid) Closes the file with the given file identifier.) the screen using any desired format. Since cond(H) is 1.) file using any desired format. fscanf(fid. Then there exists an upper triangular matrix R such that RT R = A. 7. Some Useful Linear Algebra Functions Advanced Input-Output fopen( 0 <file name> 0 .) 85 . <format string>) Behaves very similarly to the C command in reading data from a file using any desired format. The condition number of A ∈ Cn×n . Most of these discussions can be read independently of the others. an error message is printed. while if cond(A) = 1 the matrix is as nice a matrix as you could hope for — in particular. Note: A few of these functions can only be applied to full matrices. † A ∈ Rn×n is positive definite if xT Ax ≥ 0 for all x ∈ Rn and xT Ax = 0 only if x = 0. everything fits. <format string>. chol Let A ∈ Rn×n be symmetric and positive definite† . To estimate the num- ber of digits of accuracy you might lose in solving the linear system Ax = b. In practical terms. In doing many calculations it was clear that the solution was only accu- rate to 3 to 5 significant digits. fprintf(<format string>.. There is a mathematical “definition” for these terms. enter log10(cond(A)) In Section 5. It measures how “stable” A is: if cond(A) = ∞ the matrix is singular. it means that all the eigenvalues of A are positive. Some Useful Linear Algebra Functions We briefly describe in alphabetical order some of the MATLAB functions that are most useful in lin- ear algebra. which is denoted by cond(A).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. while it is sparse if it is created using the methods described in section 9. it is clear that you should lose about 13 of the 16 digits of accuracy in this calculation. the condition number is defined by condp (A) = kAkp kA−1 kp for p ∈ [1.. but in MATLAB a matrix is full if it is cre- ated using the methods described in Section 2. Behaves very similarly to the C command in writing data to a <variable 1>. Where this is not true. ∞] or condF (A) = kAkF kA−1 kF . Behaves very similarly to the C command in displaying data on <variable 1>.6×1013 . cond(I) = 1. which is a unique nonnegative integer attached to the file. we indicate which should be read first... (If A ∈ Cn×n then RH R = A. ( A ∈ Cn×n is positive definite if xH Ax ≥ 0 for all x ∈ Cn and xT Ax = 0 only if x = 0. 7. If A is nonsingular. Opens the file with the permission string determining how the <permission string>) file is to be accessed. R is calculated by >> R = chol(A) If A is not positive definite. The function returns the file identifier.) cond Note: Read the discussion on norm below first.. fprintf(fid. Thus. is a positive real number which is always ≥ 1. and others only to sparse matrices..

0.95 0. If p = 2 the command can be shortened to >> cond(A) Note that the calculation of the condition number of A requires the calculation of the inverse of A. consider the matrix 0. • If A is a sparse matrix (i.000. The determinant of A is calculated by >> det(A) det(A) = 0 if and only if A is singular. Inf. 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. (For example. The command condest calculates a lower bound to the condition number of a matrix in the 1-norm with- out having to determine its inverse. p) where p is 1. Similarly.n} . (This is discussed in detail in Section 5. Ax = b when A ∈ Cm×n is not a square matrix. where RCOND is the inverse of condest(A). Note: Sometimes we want to solve.97 I − C is singular (where I is the identity matrix) but >> C = [0. condest Note: Read the discussion on cond above first.. When MATLAB calculates A\b or inv(A).97].055969e-18. if n = 10. det( eye(size(C)) .. However. It checks if its estimate of the condition number is large enough that A is likely to be singular. 0. or 0 fro 0 . The MATLAB command condest approximates the condition number without having to calculate this inverse.95 0.05 0.e. but the Hilbert matrix is not singular for any n. the number it returns is much smaller than eps and so it seems “reason- able” that I − C is singular.3. σ1 /σmin{m.000 but the total number of elements in A is 100. 2.10*eye(100)) † 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 86 .03 C= . Results may be inaccurate. we want to generalize the condition number to nonsquare matrices.05 0. the number of nonzero elements in A is approximately 30.03. This approximation is almost always within a factor of ten of the exact value.2×10−53 . MATLAB may not be able to store A−1 . The calculation of the condition number of A ∈ Cn×n requires the calculation of its inverse.000. det Let A ∈ Cn×n .) Since we still want to know the accuracy of any solution. or find the “best” approximation to.C ) does not return 0. >> det(0. Some Useful Linear Algebra Functions It is calculated in MATLAB by >> cond(A.) Since the inverse of a sparse matrix is generally much less sparse (in fact it may have no zero elements at all).000 and A is tridiagonal† . i. • The calculation of A−1 requires approximately 2n3 flops. RCOND = 2. However. most of its elements are zero). On the other hand.e. due to round-off errors it is very unlikely that you will obtain 0 numerically unless all the entries to A are integers. >> det(hilb(10)) returns 2. If so. which might take too long if n is very large. See the discussion of this command below for further information on when it might be preferable. we discuss in Section 9 how to store only the nonzero elements of A to conserve storage. For example. 7. it also calculates condest(A). There are two reasons this might be inadvisable. it returns an error message such as Warning: Matrix is close to singular or badly scaled.

you do not need all the eigenvalues of a matrix. it requires cn flops. if A is a sparse matrix. MATLAB normally cannot determine when this occurs. We discuss this nota- tion in detail in Section 8. but it is also not singular. Frequently. eig can also calculate all the eigenvalues of the generalized eigenvalue problem Ax = λBx by >> eig(A. it requires cn2 flops where c is of “reasonable” size. in fact. You either have to use the function eigs or do eig(full(A)). you might only need the largest ten in magnitude.3. calculating only a few eigenvalues requires many. 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. 0 1]. MATLAB will very happily calculate all the eigenvalues of A by >> eig(A) It will also calculate all the eigenvectors by >> [V. 2. If you enter >> B = [1 1. B) A matrix is defective if it has less eigenvectors than eigenvalues. . eigs Note: Read the discussion on eig above first. is a much better method for determining if a square matrix is singular. Why not just use eig anyway? Calculating all the eigenvalues of a nonsymmetric A ∈ Rn×n requires (very) approximately 10n3 flops. For example. Or you might only need a few of the generalized eigenvalues of Ax = λBx. . v is called the eigenvector corresponding to λ. many fewer flops. 87 . this means that there are numerous possible arguments to this function so read the documenta- tion carefully. you cannot use eig — you will first have to do eig(full(A)). (The singular value decomposition. Note: If A is a sparse matrix. 0)T and T (−1. or . 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. or the five with the largest real part. Some Useful Linear Algebra Functions returns 10−100 .) eig Let A ∈ Cn×n . which is described below.2×10−16 ) . you cannot use eig. Note: This is the first time we have had a function return more than one argument. although they need not all be distinct. we simply state that when [V. There are always n eigenvalues of A. [V. 0)T so that. Clearly the latter eigenvector should be (−1. . namely (1. 0)T . D] = eig(B) MATLAB calculates the two eigenvalues correctly. D] = eig(A) D ∈ Cn×n 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 ∈ Cn×n . For now. but it only has one eigenvector. both of which are 1. Note: If A is sparse. or the one which is smallest in magnitude. If A is a full matrix. which can take a very long time if n is very large. 7. A scalar λ ∈ C is an eigenvalue of A if there exists a nonzero vector v ∈ Cn such that Av = λv . On the other hand. the matrix 1 1 B= 0 1 is defective since it has two eigenvalues. eigs can do all of this. Of course. However. there is only one eigenvector. but it finds the two eigenvectors (1. For example.

055969e-18.) inv To calculate the inverse of the square matrix A ∈ Cn×n enter >> inv(A) The inverse of A. in addition. Entering >> U(3. (Try it!) In other words.8. P] = lu(A) where A is the singular matrix defined earlier. 88 . 7 8 9].3) displays 1. where I ∈ Rn×n is the iden- tity matrix. all the elements on the main diagonal are 1. enter >> op. be careful — and read (and understand) all warning messages. 3.disp = 0 >> eigs(A. ( RCOND is the inverse of a numerical approximation to the condition number of A. a unit lower triangular matrix L † . it must be unique. all the elements of U on the main diagonal are nonzero. but all the entries will be Inf. RCOND = 2. If you enter >> A = [1 2 3. ‡ P is a permutation matrix if its columns are a rearrangement of the columns of I. 1≤i≤n † A unit lower triangular matrix is lower triangular and. which clearly should be zero as we discussed in Section 1. MATLAB still does try to calculate the inverse. U.1102e-16.1) 7 8 9 also does not have an inverse. but it thinks it is likely. MATLAB will complain that Warning: Matrix is singular to working precision. If such a matrix exists. To calculate the largest 3 eigenvalues of A in magnitude without generating any diagnostics. For example. see condest above. 0 LM 0 . [L. It will display the inverse matrix. If you ask MATLAB to calculate the inverse of A. The MATLAB command lu calculates these matrices by entering >> [L. P] = lu(A) If A is invertible. U. Results may be inaccurate. is a matrix such that AA−1 = A−1 A = I. and a permutation matrix P ‡ such that LU = PA .4. exist. The above matrix was very simple. 4 5 6. because of round-off errors. it will complain that Warning: Matrix is close to singular or badly scaled. 7. the matrix 1 2 A= 2 4 does not have an inverse. op) ( op. The matrix 1 2 3 A = 4 5 6 (7. if you multiply this matrix by A the result is nowhere close to I. MATLAB is not positive that A is singular.disp is a structure. Then there exists an upper triangular matrix U. ∞) kxkp = i=1 max |xi | if p = ∞ .) That is. Some Useful Linear Algebra Functions Also. Of course. which was discussed in Section 3. 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.) The pth norm of a vector is defined by X n 1/p p |xi | if p ∈ [1. (It was briefly discussed in Section 2. this command generates lots of diagnostic output.5. MATLAB cannot always tell whether this matrix does. u33 should be zero. If you try to take the inverse of this matrix. in fact. denoted by A−1 . lu Let A ∈ Cn×n . However.

the Frobenius norm. If p = 2 the command can be shortened to >> norm(A) There is another matrix norm. There is another use for the qr function. i.k is the last nonzero diagonal element of R.i+1 | ≤ |ri..e. † Q ∈ Rm×m is orthogonal if Q−1 = QT . which is defined for A ∈ Cm×n by m X X n 1/2 2 kAkF = |aij | i=1 j=1 and is calculated in MATLAB by entering >> norm(A. 7. or Inf. 2. or ∞ it is calculated in MATLAB by entering >> norm(x. p) where again p is 1. p) where p is 1. or Inf.k | for all i. R. 2. then the first k columns of Q are an orthonormal basis for the range of A and the final n−k columns are an orthonormal basis for the null space of AT . Then there exists an orthogonal matrix Q ∈ Rm×m † and an upper triangular matrix R ∈ Rm×n such that A = QR . 2. null Let A ∈ Cn×n . In this case AE = QR for some permutation matrix E and >> [Q. ( Q ∈ Cm×m is unitary if Q−1 = QH . If rk. We can calculate an orthonormal basis for the columns of A by >> orth(A) qr Let A ∈ Rm×n . The command orth is preferable if all you want is an orthonormal basis for R(A). R] = qr(A) It is frequently preferable to add the requirement that the diagonal elements of R be decreasing in magni- tude. There exists a matrix Q ∈ Rm×n with orthonormal columns and an upper triangular matrix R ∈ Rn×n such that A = QR .) We calculate Q and R in MATLAB by entering >> [Q.) 89 . E] = qr(A) One reason for this additional requirment on R is that you can immediately obtain an orthonormal ba- sis for the range of A and the null space of AT . Some Useful Linear Algebra Functions For p = 1. |ri+1. ∞] x6=0 kxkp and is calculated in MATLAB by entering >> norm(A. (If A ∈ Cm×n then there exists an unitary matrix Q ∈ Cm×m and an upper triangular matrix R ∈ Cm×n such that A = QR. 0 fro 0 ) It is equivalent to norm(A(:)). We can calculate an orthonormal basis for the null space of A by >> null(A) orth Let A ∈ Cn×n . If p = 2 the command can be shortened to >> norm(x) The pth norm of a matrix is defined by kAxkp kAkp = max for p ∈ [1.

2. § In fact. their eigenvalues are nonnegative.7×10−5 . 4.) ‡ For example. (If A ∈ Cm×n then U ∈ Cm×m and V ∈ Cn×n are unitary matrices and Σ ∈ Rm×n is again a diagonal matrix with real nonnegative elements in decreasing order. We include it here for completeness.3. and 8. 4. 1.7×10−11 . 5.5×10−8 . the eigenvectors of AH A are the columns of V and those of AAH are the columns of U.4×10−18 according to MATLAB. σ1 ≥ σ2 ≥ · · · ≥ σmin{m.7×10−2 .† Their nonzero eigen- values are the squares of the singular values of A.1079×10−16 . Although A need not be a square ma- trix. and so its rank is truly n. 5. Some Useful Linear Algebra Functions It is calculated by >> [Q. and 2.4368. A can be decomposed into A = UΣVT where U ∈ Rm×m and V ∈ Rn×n are orthogonal matrices and Σ ∈ Rm×n is a diagonal matrix (although not necessarily square) with real nonnegative elements in decreasing order. R] = qr(A. 5. 1. the eigenvectors of AT A are the columns of V and those of AAT are the columns of U. 0) This is equivalent to applying the Gram-Schmidt algorithm to A. It is calculated by using the singular value decomposition.n} ≥ 0 .‡ In addition. 1.3×10−1 .4×10−16 . AH A and AAH are both square Hermitian matrices. For example. Following Principle 1. both AT A ∈ Rn×n and AAT ∈ Rm×m are square symmetric matrices.4×10−14 . (If A is complex.8×100 .6×10−3 . 7. to see that 1 2 3 4 A = 5 6 7 8 9 10 11 12 has rank 2.§ † The eigenvalues of a real square symmetric matrix are nonnegative. 90 . rank Let A ∈ Cm×n .) The best numerical method to determine the rank of A is to use its singular values. you can see there is no separation between the singular values which are clearly not zero and the ones which are “close to” eps. The m eigenvalues of AAT consist of the squares of these n singular values and m−n additional zero eigenvalues.2×10−17 . 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. you cannot conclude that any of these singular values should be set to 0. Clearly the third singular value should be 0 and so A has 2 nonzero singular values and so has a rank of 2.) Thus. Our “best guess” is that the rank of this matrix is 15. 1. (If A is complex. However. svd Let A ∈ Rm×n .3×10−6 .3×10−4 . S. use the svd command to find that the singular values of A are 25. if m > n there are n singular values and their squares are the eigenvalues of AT A. V] = svd(A) The diagonal elements of Σ are called the singular values of A. (The eigenvalues of a complex square Hermitian matrix are real and nonnegative. 1.7226. 4. which we discuss below. the Hilbert matrix of order 15 has singular values 1. 1. Thus. if you enter >> rank( hilb(15) ) you obtain 12. which we discuss below. On the other hand. pinv The Moore-Penrose pseudoinverse has already been discussed in Section 5.3×10−13 . so that MATLAB is off by three. 2. 9.) These matrices are calculated by >> [U. it can be proven that the Hilbert matrix of order n is nonsingular for all n. That is.8×10−9 .

This greatly increases the read- ability of the code for human beings. norm(A) Calculates the norm of a matrix. sometimes there is a need for finer control over the elements of matrices and the ability to test. rank(A) Estimates the rank of a matrix. it is very important to use indentation to indicate the structure of a code. qr(A) Calculates the QR decomposition of a matrix. and eigenvectors if desired. MATLAB can do very complicated matrix operations. Flow Control and Logical Variables MATLAB has four flow control and/or branching instructions: for loops. 91 . p) calculates the p-norm. of a square matrix. Although prior familiarity with a high-level programming language is useful. and eigenvectors if desired. Notation: All of these instructions end with an end statement. Flow Control and Logical Variables Some Useful Functions in Linear Algebra chol(A) Calculates the Cholesky decomposition of a symmetric. There are numerous possible arguments to this function so read the documentation carefully. norm(A. null(A) Calculates an orthonormal basis for the null space of a matrix. eigs Calculates some eigenvalues. cond(A) Calculates the condition number of a square matrix. eig(A) Calculates the eigenvalues. and switch branching tests. of a square matrix. cond(A.1. inv(A) Calculates the inverse of a square invertible matrix. positive definite square matrix. det(A) Calculates the determinant of a square matrix. 8.1.. as we do in the remainder of this tutorial. and branch on. 8. while loops. condest(A) Calculates a lower bound to the condition number of A in the 1-norm. The general form of the for loop is for <variable> = <expression> <statement> . However. lu(A) Calculates the LU decomposition of a square invertible matrix. orth(A) Calculates an orthonormal basis for the range of a matrix. MATLAB’s programming language is so simple that it can be learned quite easily and quickly.. and it is frequently difficult to determine the extent of these instructions. logical conditions. svd(A) Calculates the singular value decomposition of a matrix. p) calculates the p-norm. norm(v) Calculates the norm of a vector. norm(v. Programming in MATLAB Using the commands we have already discussed. The elements of the row vector <expression> are stored one at a time in the variable and then the statements up to the end statement are executed. p) calculates the condition number in the p-norm. <statement> end where the variable is often called the loop index. if-else branching tests.† For exam- † <expression> can be a matrix in which case each column vector is stored one at a time in i. Thus. 8.

Caveat emptor! A more practical example of the use of a for loop is the generation of the Hilbert matrix of order n. you can define the vector x ∈ Rn where xi = i sin(i2 π/n) by x = zeros(n. For this we need the if branch. This saves computational time and makes the code more understandable. Of course. end ˆ However. 8. For example. end ˆ (The first line is not actually needed. 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. Some examples of logical expressions are i == 5 x(i) >= i imag(A(i.j) = 1/(i + j . you can also generate the vector by >> x = [1:n] 0 . √ Warning: In using i as the index of the for loop.1 < x(1) + x(i) 3 ˆ Is i equal to 5? Is xi ≥ i? Is the imaginary part of ai. which we now describe. 1). ˜ † Compare the results of 0 >> Yes 0 == 0 yes 0 and 0 >> Yes 0 == 0 no 0 92 .* sin( [1:n] 0 . i and j have just been redefined to be n instead of −1 .1).) In fact. 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. 2 *pi/n ) ˆ which is certainly “cleaner” and executes much faster in MATLAB.. for i = 1:n for j = 1:n H(i.1.i)) = 0 ˜ sin(1) . Caveat emptor! for loops often have branches in them. but it allows MATLAB to know exactly the size of the final vector before the for loops begin. <statement> end where the statements are evaluated as long as the <logical expression> is true. the entire for loop could have been entered on one line as >> for i = 1:n x(i) = i * sin( i 2 *pi/n ). end end Warning: In using i √and j as the indices of the for loops. which we have already discussed a number of times. for i = 1:n x(i) = i * sin( i 2 *pi/n ). Flow Control and Logical Variables ple. it is discussed in more detail in Section 8. This is easily done using two for loops by H = zeros(n). mathemati- cally we cannot apply the other four relational operators. However. for readability it is best to split it up and to indent the statements inside the loop.5. i has just been redefined to be n instead of −1 .† Instead.i nonzero? Is sin 1 − 1 < x1 + x3i ? We can compare complex numbers to determine whether or not they are equal. The simplest form of the if statement is if <logical expression> <statement> . Warning: String variables cannot be compared by == or =. if a and b are text variables..

Flow Control and Logical Variables enter >> strcmp(a. statement group 2 is evalu- ated if the <logical expression 2> is true. elseif <logical expression r> <statement group r> else <statement group r+1> end where statement group 1 is evaluated if the <logical expression 1> is true. = Not equal to. etc. “NOT” (denoted by “ ”). b) The result is true if the two character strings are identical and false otherwise. These act on false ˜ or true statements which are represented by numerical values: zero for false statements and nonzero for 93 . then none of the statement groups are executed. b) Compares strings. “OR” (denoted by “ |”).. and “EXCLUSIVE OR” (invoked by the function xor ). MATLAB calculates this as a nu- merical value which is returned in the variable ans.1. A second form of the if statement is if <logical expression> <statement group 1> else <statement group 2> end where statement group 1 is evaluated if the <logical expression> is true and statement group 2 is evaluated if it is false. elseif <logical expression r> <statement group r> end and if <logical expression 1> <statement group 1> elseif <logical expression 2> <statement group 2> elseif <logical expression 3> <statement group 3> .. If it occurs and if none of the previous logical expressions is true. > Greater than. <= Less than or equal to. When a logical expression such as >> i == 5 is evaluated. Relational Operators < Less than. statement group r+1 is evaluated.. == Equal. the result is either the logical value “TRUE” or “FALSE”. ˜ strcmp(a. >= Greater than or equal to.. The value is 0 if the expression is false and 1 if it is true. MATLAB also contains the logical operators “AND” (denoted by “&”). The final else statement is not required. The final two forms of the if statement are if <logical expression 1> <statement group 1> elseif <logical expression 2> <statement group 2> elseif <logical expression 3> <statement group 3> . 8. If it does not occur and if none of the logical expressions are true.

0 ).. otherwise c is false (i. • the relational command >> c = xor(a.e. The logical vari- able can be set by c = logical(1) or c = logical(0) — and now c is a logical variable. (true) or 0 (false). The second MATLAB loop structure is the while statement. >> c = a || b returns a (scalar) logical true if either input evaluates to true.. The preferred ways to set a logical variable are the following. while 1 + ep > 1 ep = ep/2. • the relational equation >> c = a ˜ means that c is true (i. Returns logical 1 (true) or 0 (false). otherwise c is false (i.. The statement >> c = a && b returns a (scalar) logical true if both inputs evaluate to true (so if they are variables they both must be scalars). b) means that c is true (i. otherwise c is false (i.e.1. <statement> end where the statements are executed repeatedly as long as the <logical expression> is true. 1 ) if a and/or b is true (i... otherwise c is false (i. Returns logical 1 A|B OR.e.e. The difference from & is that if a is false then b is not evaluated..e. if a and b are real numbers then • the relational equation >> c = a & b means that c is true (i. This is called short-circuiting the AND and OR operators. The general form of the while loop is while <logical expression> <statement> . a && b Short-circuit AND... a is true. but c is now not a logical variable. 1 ) only if both a and b are true (i.. 1 ) if a is false (i. Flow Control and Logical Variables true statements.e. but a numerical variable. ˜xor(A. Only evaluates b if a is false. 0 ). 1 ) if exactly one of a and b is true (i. nonzero). nonzero).e. For exam- ple.e. 0 ). Similarly. • the relational equation >> c = a | b means that c is true (i. C++. Thus. Fre- quently — but not always — the variable can be set by c = 1 or c = 0. 8. Frequently — but not always — a numerical variable can be used in- stead of a logical variable.. and Java). a || b Short-circuit OR. 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 94 . A simpler way to set the logical variable c is c = true or c = false.e..e. Only evaluates b if A NOT. 0 ). If a is true then b is not evaluated (as in C...e. Logical Operators A&B AND.. 0 ). In the above statements c is a logical variable which has the logical value “TRUE” or “FALSE”. eps can be calculated by ep = 1. There are second logical operators “AND” (denoted by && ) and “OR” ( || ) which are sometimes used. B) EXCLUSIVE OR. nonzero).e.

Use false or false(n) or false(m. Use true or true(n) or true(m. then all the values must be surrounded by curly brackets. then none of the statement groups are executed.. This terminates the execution of the innermost for loop or while loop... then statement group r+1 is evaluated. elseif Used with the if statement. <Value 2c>. Elementary Logical Matrices true Generates a logical matrix with all elements having the logical value true. Flow Control break Terminates execution of a for or while loop. while Repeats statements as long as an expression is true.1. <Value 2m>} <statement group 2> . case Part of the switch command. false Generates a logical matrix with all elements having the logical value false. The statements following it are executed if its value or values are a match for the switch expression. The switch command executes particular statements based on the value of a variable or an expression. 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>. Warning: The switch command is different in MATLAB than in C in two ways: First. switch. It causes the next iteration of the for or while loop to begin immediately.. <Value 2b>. The statements following it are executed if no case value is a match for the switch expression. second. Flow Control and Logical Variables command as in C. continue Begins the next iteration of a for or while loop immediately. if.. end Terminates the for. in MATLAB the case statement can contain more than one value. n). switch Selects certain statements based on the value of the switch expression. The continue statement is related to break. If it occurs and if none of the values match the variable or expres- sion. If it does not occur and if none of the values match. And. where statement group 2 is evaluated if the variable or expression has values <Value 2a> or <Value 2b> or <Value 2c>. for Repeats statements a specific number of times. (Note that if a case has more than one value. in MATLAB only the statements between the selected case and the following one or the following otherwise or end (whichever occurs first) are executed. if Executes statements if certain conditions are met. else Used with the if statement. in C it can only con- tain one.) The final otherwise is not required. otherwise Part of the switch command. 95 . 8. in C all the state- ments following the selected case are executed up to the next break or the end of the block. etc. . n). and while statements. Its general form is switch <variable or expression> case <Value 1> <statement group 1> case {<Value 2a>.

quickly. Also. MATLAB’s relational and logical operators can also be applied to vectors and matrices. generates the matrix C where 1 if fij > 0. Again the elements of C are all 0 or 1. 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. In this way.5 nr elements = nr elements + 1. 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. To show the power of these MATLAB commands. If A.5. 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 .5 n cij = 0 otherwise. its data type is “logical” not “numeric”. >> C = A ˜ means cij = aij .5) The relational expression F > 0. the relational equation >> C = A rop c is defined when c is a scalar. for i = 1:m for j = 1:n if F(i. For example. to make the meaning clearer. B ∈ Rm×n then the relational equation >> C = A rop B is evaluated as cij = aij rop bij . Since the number of ones is the result we want. suppose we have entered >> F = rand(m. where rop is one of the relational operators defined previously. 8. and ˜ >> C = xor(A. Multiplying this new matrix elementwise with F zeroes out all 96 . and efficiently since the relational expression >> C = F > 0.5 by zero. >> C = A | B means cij = aij | bij .5 ) ) or >> sum(sum(C)) or >> sum(C(:)) And suppose we want to replace all the elements of F which are ≤ 0. it can be coded much more simply. This is easily done by >> F = F.5.5). algorithms that would normally require flow control for coding in most programming languages can be coded using simple MATLAB commands. it is needed much less fre- quently than in typical high-level languages. end end end nr elements However. >> C = (F > 0. simply enter >> sum( sum( F > 0. n) and now we want to know how many elements of F are greater than 0. We can code this as nr elements = 0. Matrix Relational Operators and Logical Operators 8.5 generates a matrix with zeroes in all the locations where we want to zero the elements of F and ones otherwise. B) means cij = xor(aij .2. that is.2. bij ).*(F > 0.j) > 0. Matrix Relational Operators and Logical Operators Although MATLAB does have a quite powerful programming language. C is a logical array. or.

[1:m]’. we can calculate the other by >> ijA from iA jA = sub2ind(size(A). n] = size(A). π)T then the resulting vector is (2. we showed how to replace all the elements of F which are ≤ 0.e. As a simple example of the power of this command we can add 10 to every nonzero element of A by >> ijA = find(A). >> k = strfind(str. For example. of the nonzero elements. If we use two indexes we are treating A as a matrix. Then the element A(3. Matrix Relational Operators and Logical Operators the desired elements of F. jA] = find(A) The two column vectors iA and jA contain the rows and columns. Note: There is a similar function which finds if a substring is contained in a string. 4. For example.) For example. valueA] = find(A) Now is as good a time as any to discuss a fact about matrices which might be confusing. we can choose one column randomly from each row of A by >> r = randi(n. We can access and/or modify elements of a matrix A using either one index or two. jA). We can also find the elements of a vector or a matrix which satisfy a more general property than being nonzero. >> [iA. jA from ijA] = ind2sub(m. (Recall that nonzero can also mean “TRUE” so that this command finds the elements where some condition is true. >> ijA = find(A). The command >> find(x) generates a column vector containing the indices of x which are nonzero. 0. as a specific example. r). >> random columnsA = A(ij). >> x(ix) = x(ix) + 10. The command >> find(A) first transforms A to a column vector (i. 5. if x = (0. Suppose that A ∈ R6×4 . >> A(ijA) = A(ijA) + 10 Or we can work with the matrix directly by entering >> [iA. find can also be applied to a matrix. jA. 7)T .2) is also A(9).1) is also A(3) and the element A(3. A method which 97 . And. And we can switch back and forth between the two.5) >> F = F. Knowing one. the result is the empty matrix [] and the following state- ment is not executed. >> [iA from ijA. respectively. iA. 8.5 by −π using >> C = (F > 0. to find the locations of all the elements of x which are greater than 5 enter >> find(x > 5) and to find the locations of all the elements of x which are greater than 5 and less than 8 enter >> find( (x > 5) & (x < 8) ) We can find the number of elements which satisfy this last property by entering >> length( find( (x > 5) & (x < 8) ) ) Previously. 4.. 0. pattern) returns the starting index for any and all occurrence ofs pattern in str.pi*( C) ˜ Shortly we will present two easier ways to do this. 1). We can also replace all the elements of F which are ≤ 0. ijA). A(:) ) and then determines the locations of the nonzero ele- ments. We can add 10 to every nonzero ele- ment of x by >> ix = find(x).2. >> ij = sub2ind(size(A). Note: If no element of the vector x is nonzero. −1. m. 1. when we enter >> [m. 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.*C . We can also find the locations of the nonzero elements and their values by >> [iA.5 by −π. while if we use one we are treating A as the column vector A(:). jA] = find(A) we have the elements of A(:) stored in ijA and the elements of A stored in iA and jA.

0] and c = [0 0 1 1 1] where “0” denotes false and “1” denotes true. Matrix Relational Operators and Logical Operators does not require any multiplication is >> ijF = find(F <= 0. so that v = [0 . we take a specific and very simple example.5) ) = -pi The “beauty” of MATLAB commands such as these is they are so easy to use and to understand (once you get the hang of it) and they require so few keystrokes.5 .2.5) = -pi to combine everything into a single statement. 8.75 1.) This requires some explanation. To see that D is a logical variable and F is not. c is a logical vector and v(c) deletes the elements of v which are “false”.25:1]. otherwise 0 is returned. How does MATLAB know that D should be used to “mask” the elements of F? The answer is that D is a logical matrix because it was defined using a logical operator. 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”. nothing is done. To explain logical arrays more clearly. Recall that ijF is a vector which contains the actual locations of the el- ements we want to zero out. When applied to a matrix. whereas D is a matrix of ones and zeroes which explicitly shows which el- ements should be zeroed.5) rather than the vector ijF.25 . The command >> any(x) returns 1 if any element of the vector x is nonzero (i. for every element of D which is zero. enter >> F(2*D) We can also convert a non-logical variable to a logical one by using the MATLAB command logical. The result of >> v(c) is [. Enter >> v = [0:.0].5). On the other hand >> iv = find(v < . and only logical matrices and vectors can be used as “masks”. >> F(ijF) = -pi or even >> F( find(F <= 0. The difference between c and iv is that c is a logical vector and iv is a scalar vector. we can check 98 ..5 . returns iv = [1 2] and >> v(iv) = []. the corresponding element of F is replaced by −π.75 1. The matrix D is being used here as a “mask” to determine which elements of F should be replaced by −π: for every element of D which is nonzero. enter >> islogical(D) >> islogical(F) or >> class(D) >> class(F) And to see what happens when you try to use a non-logical variable as a “mask”.0].5).e. it operates on each column and returns a row vector. slightly different method uses the matrix >> D = (F <= 0. MATLAB also has two functions that test vectors and matrices for logical conditions. That is. 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. >> c = (v >= . returns v = [.75 1.5). For example. We can use D to determine which elements of F should be replaced by zero by >> F(D) = -pi (We can even use >> F(F <= 0. “TRUE”).5 . Another.

the status of the elements of vectors and matrices. 2) + tril(A. -2) ) ) Here we check all the elements of A except those on the main diagonal and on the two adjacent ones. 0 ) ) A result of 1 means that A is identical to AT . For ex- ample.e. A result of 1 means that at least one other element is nonzero. -2) ) ) ˜ instead. It is also easy to check if two arrays (including structures and cells) have exactly the same contents.2. The complementary function all behaves the same as any except it returns 1 if all the entries are nonzero (i. enter exist( 0 A 0 ) See the table below for more details and more functions. The command >> isequal(A. 2) + tril(A. and even of their existence. B) returns true if all the contents are the same and false otherwise. Matrix Relational Operators and Logical Operators whether or not a matrix is tridiagonal by >> any( any( triu(A. To determine if the matrix A even exists. This means that (nonempty) arrays must have the same data type and be the same size. For example. For completeness we mention that MATLAB has a number of other functions which can check the status of variables. you might want to zero out all the elements of a matrix A which are Inf or NaN. If we want a result of 1 to mean that A is tridiagonal we can use >> any( any( triu(A. you can determine if a matrix is symmetric by >> all( all(A == A. 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. The command >> any(A) operates columnwise and returns a row vector containing the result of any as applied to each column. 99 . “TRUE”).. 8.

. Each function m-file contains its own function workspace which is independent of the base workspace and every other function workspace. 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. sub2ind Converts indices of a matrix A from A.... Thus you do not need to understand the internal workings of a function file. ind2sub Converts indices of a matrix A from A(:). . If it is. []. The output arguments must appear to the left of the equal sign: if there is only one output argument. 8. isinf Generates a matrix with 1 in all the elements which are Inf and 0 otherwise. to A.. <out 1>.e. which are simply an easy way to collect a number of state- ments and execute them all at once. The first line of the file <file name>. Function M-files Logical Functions all True if all the elements of a vector are true. isnan Generates a matrix with 1 in all the elements which are NaN and 0 otherwise. <in n>) where the name of the function must be the same as the name of the file (but without the extension). . Unlike script files.e. is function <out> = <function name>(<in 1>.3. you only need to understand what the input and output arguments represent. <in 2>. 8. Function m-files. isempty True if the matrix is empty. . The input arguments are <in 1>. . <in n>) or function [<out 1>.. operates on the columns of a matrix. any True if any of the elements of a vector are true. are similar to functions or pro- cedures or subroutines or subprograms in other programming languages. 5 if this is the name of a built-in MATLAB function. ischar True for a character variable or array.. i. if there is more than one. . etc.. which includes all variables created in script m-files which have been executed. strfind Find any and all occurrences of a substring in a string. isequal Tests if two (or more) arrays have the same contents. to A(:). on the other hand. the column vector form. Function M-files We have already discussed script m-files. The base workspace contains all the variables created during the interactive MATLAB session. The complete first line. 2 if this is the name of an m-file. exist( 0 <name> 0 ) False if this name is not the name of a variable or a file. islogical True for a logical variable or array..3. <out>. i. the matrix for.m must begin with the keyword function. i. isfinite Generates a matrix with 1 in all the elements which are finite (i. find The indices of a vector or matrix which are nonzero. .. Without this word. function files must be constructed in a specific way. not Inf or NaN ) and 0 otherwise. because the extension is “m”. we discuss this topic in 100 . called the function definition line. Note: The generic term for script files and function files is m-files. Ordinarily. they must be separated by commas and must be enclosed in square brackets. operates on the columns of a matrix... Variables in MATLAB are stored in a part of memory called a workspace. logical Converts a numeric variable to a logical one. this function returns: 1 if this is the name of a variable.. The only way to “connect” these workspaces is through the arguments of a function or by using the global command (which we will discuss shortly). it appears by itself. the file is a script file. <out m>] = <file name>(<in 1>. the matrix form.e.e. There is great flexibility in the number and type of input and output arguments. the column vector form...

The only detail we want to mention now is that the input arguments are all passed “by value” as in C. Function M-files great detail later.3.† Warning: The name of the . 8.) Thus. the input arguments can be modified in the function without affecting any input variables in the calling statement. the values of the input arguments are stored in temporary variables which are local to the function. (That is.

there is one technical detail it is important to consider be- fore it trips you up: how does MATLAB find the m-files you have created? Since MATLAB contains thousands of functions. i. We show the order here and then discuss the items in detail throughout this subsection.) Warning: When you begin a MATLAB session. If the m-file is not in the current directory. you can add one or more directories at the beginning of the search path by >> addpath( 0 new directory #1 0 . (4) It checks if the current directory has a subdirectory called “private”.. can be searched for keywords by entering >> lookfor <keyword> Make sure this first comment line contains the name of the command and important keywords which de- scribe its purpose. MATLAB does not actually pass all the input arguments by value. 0 new directory 0 ) (The former puts “new directory” at the beginning of the search path while the latter puts it at the end. it always checks if the subdirectory “matlab” exists in † If you are worried because passing arguments by value might drastically increase the execution time of the function. Comment lines should immediately follow. this is not an easy task. If you have created a subdirectory called “matlab” in your main directory. 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! 101 .. including on a line following a MATLAB state- ment.e. MATLAB checks if the file <function name>. Thus. Note: Comments can be placed anywhere in an m-file. Instead. the second line of the file. it is passed “by reference”.m exists in this subdirectory.. the input argument is the actual variable used in the calling statement and not a local copy. the primary function.le and the name of the function must agree.m. A comment line begins with the percent character.) In this way you get the benefit of “call by value” without any unnecessary overhead. or a nested function in the current scope.. When you type >> help <function name> all these lines of documentation are typed out. if it does. it searches for the function in a particular order. If you type type <function name> the entire file is printed out.. To be precise. these lines are called the online help entry for the function.. the simplest way to enable MATLAB to find it is have the subdirectory in your search path. “%”. If you type >> path you will see all the directories that are searched. All comment lines which immediately follow the function definition line constitute the documentation for this function. (That is. an input variable is only passed by value if it is modified by the func- tion. the first line of documentation. path) or >> path(path.) Alternately. Note from (3) that MATLAB searches in the current directory for the function by searching for the m- file with the same name.) (3) It checks if the file <function name>. In addition.m exists in the current directory. you can put your m-files in this subdirectory and be sure that MATLAB will find them. we want to reassure you that this does not happen. this is usually the first directory searched (unless the search path has been modified). Once MATLAB has determined that the word is not a variable. i. This is also the name of the com- mand that executes the function. i.e. (2) It checks if <function name> is a function. If an input variable is not modified. (1) It checks if <function name> is a built-in function (i. You can also add directories to the search path by >> path( 0 new directory 0 . .e. (5) It searches the directories in the search path for the file <function name>. in the current file. 0 new directory #2 0 . a subfunction. coded in C).e. (We discuss all these terms shortly. The initial comment lines in a script file and the comment lines in a function file which immediately follow the first line are special: they appear on the screen when you type >> help <function name> Before discussing functions at great length.

1). while if initialize = true it is. function a = prealloc(n. you can force the function to abort by entering error(<string>) If the string is not empty. true). The first line of the documentation includes the name of the function as well as a brief description that lookfor uses. The following lines of documenta- tion also appear on the screen if we enter >> help hilb local Note: The above code is not presently used in MATLAB (although it was in early versions. the string is displayed on the terminal and the function is aborted. four hundred) times as fast as >> prealloc(100000.j) = 1/(i+j-1). since i and j are local to this function.3. If you create this subdirectory after you start a MATLAB session. which can appear anywhere in the function and force an immediate end to the function. H = zeros(n). it will not be in the search path. We follow by defining H to be an n×n matrix. this statement can greatly in- crease the speed of the function because space can be preallocated for the matrix. consider the following code. We begin with a simple example of a function file which constructs the Hilbert matrix (which we have already used a number of times). for i = 1:n for j = 1:n H(i. you can use the return command. on the other hand. Now we return to our discussion of creating functions. Note: The return function also works in script m-files Alternately. end a(1) = 1. We find that >> prealloc(100000. One feature of function files which is occasionally very useful is that they can have a variable number of 102 . Function M-files your main directory. function H = hilb local(n) % hilb local: Hilbert matrix of order n (not from MATLAB) % hilb local(n) constructs the n by n matrix with elements 1/(i+j-1). % This is one of the most famous examples of a matrix which is % nonsingular. but which is very badly conditioned. √ Note that i and j are redefined from −1 since they appear as for loop indices. this does not have any effect on the calling code when this command is executed. Instead. false).) The actual MATLAB code for this function is shown in Section 8. the statement is ignored. if the string is empty. this might be difficult to accomplish. 8. If we type >> Z = hilb local(12) then the matrix Z contains the Hilbert matrix and H is undefined.do not if initialize == true a = zeros(n. Normally functions are completed when the end of the file is reached (as above).preallocate the vector % = false . end If initialize = false the vector a is not preallocated. If the flow control in a function file is complicated enough. runs over 400 (that’s right. However. initialize) % prealloc: testing how well preallocating a vector works % n = the size of the vector % initialize = true . for i = 2:n a(i) = a(i-1) + 1. end end The input argument is n and the output argument is H. Also.5. Although not essential. For example. the variable H is local to the function.

enter >> [V. If x is a vector. . and a are all vec- tors. Similarly. 2. MATLAB can also determine the number of input and output arguments: nargin returns the number of input arguments and nargout returns the number of output arguments. a single value) or it can be a vector. xi = 0 and a = 1 ˆ % if only x and xi are input. Note: On the right side of an equation. more simply. If. .2. out2] = spruce(x. enter >> eigval = eig(A) However. a) = e−a(x−ξ) sin x . and. f(x. . if only the eigenvalues of a matrix A ∈ Cn×n are desired. [V D] or [V.e. a) % spruce: a silly function to make a point. x.xi.e. D] is the matrix whose initial columns come from V and whose final columns come from D. We can “spruce” this function up to have default values for ξ and a and also to calculate its derivative with the following function file. one can be a character variable and the other a matrix. function [out1.a) and f’(x. V and D can be completely different variables. ξ. .*sin(x). elseif nargin == 2 a = 1. suppose we want to create a function file which calculates 2 f (x.a) are calculated if nargin == 1 xi = 0..a) is calculated % if two output arguments. ξi .xi. i. xi.xi. ξ. . p) if p = 1. and all the values can be calculated in one call to spruce. Also. n . while if there are two output arguments then both f (x) and f 0 (x) are calculated. 2. . (x1 . x2 . .*(cos(x) . ai ) = e−ai (xi −ξi ) sin(xi ) for i = 1. For example. the norm of a vector x can be calculated by entering >> norm(x. while ξ and a are scalars. all the values can be calculated in one call to spruce. by >> norm(x) if p = 2. A common error which writing a function m-file is forgetting that the argument(s) might be vectors or 103 . if nargout == 2 ˆ out2 = exp(-a. . 2).*(x-xi). D] = eig(A) where D ∈ Cn×n is a diagonal matrix containing the n eigenvalues on its diagonal and the corresponding eigenvectors are found in the same columns of the matrix V ∈ Cn×n . a) = e−a(xi −ξ) sin(xi ) for i = 1.*(x-xi). end out1 = exp(-a. ξ. a = 1. 8. Similarly. . .*sin(x)). For example. D] denotes the two output arguments which are re- turned by a function. then the function is 2 f (xi . 2. For example.a) = sin(x)*exp(-a*(x-xi) 2) % if only x is input. note that x can be a scalar (i. f(x..*a. [V. Function M-files input and output variables.*(x-xi).3. if both the eigenvalues and eigenvectors are desired. This requires that V and D be matrices which have the same number of rows.xi. or Inf or. a = 1 % if only one output argument. n . xn )T . then the function is 2 f (xi . ξ and a can each be a scalar or a vector. . f(x. again. 2). 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. On the left side. . If there is only one output argument then only f (x) is calculated. on the other hand.

how do you debug your m-file? There are a number of simple techniques you can use and we discuss them in turn. >> myheaviside([-3:3]) returns ans = 0 0 0 0.) You can even turn these pauses on and off by using pause on and pause off. we mentioned the Heaviside step function in Some Common Real Mathematical Functions on page 13.5. Function M-files matrices.0000 1. MATLAB can get away with this because most matrix operations can be performed directly — unlike in most other programming languages.01) should be supported on most platforms.3. We could write it as function Y = myheaviside scalar(x) if x < 0 y = 0.5. >> myheaviside scalar([-3:3]) returns ans = 1 Note that the function does not return an error message — it simply returns an incorrect result. For example. Note: Occasionally. When loops are involved (either using for or while statements). but pause(0. you will forget that you have put the command 104 . What do you do if the result is incorrect? In other words. will work in all cases. (The input and output arguments are capitalized to indicate that they can be matrices. However. but pointed out that it is in a toolbox which you might not have. This can fre- quently lead to an understanding of where the calculation first went wrong. When you are entering one statement at a time in the text window. the printed output can seem to be endless (and it is endless if you are in an infinite loop). (Inci- dentally. this is not true of function m-files since all the local variables in the function disappear when the function ends. end but this will only work if x is a scalar. You only need to write your own function if MATLAB cannot already do what you want. And it is usually impossible to read the out- put since it is zipping by at (what appears to be) nearly the speed of light! The pause command can slow down or even stop this output. For example. Y(X==0) = 0. 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. however. with any m-file you can selectively remove semicolons so that intermediate results are printed out. myheaviside scalar([-6:0]) also returns 1. If you want to become proficient in this language. (This is computer dependent.0000 We have now presented all the essential features of the MATLAB programming language. Y(X>0) = 1. In a script m-file intermediate calculations are normally not printed out. Of course. 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. Now that we have discussed the essentials of programming in MATLAB. simply use the type command to look at the coding of some functions. However. and it cer- tainly is a “minimal” language. else y = 1. but they are still available to look at.5000 1. This is probably the most common method of debugging programs — no matter what programming language is being used. function Y = myheaviside(X) Y = zeros(size(X)). you immediately see the result of your calculation and you can determine whether or not it is correct. elseif x == 0 y = 0. 8.) The following function. it is necessary to discuss how to program correctly.0000 1.) For example.

There are two ways to run the debugger: you can type the debugger commands into the workspace. It stops execution of the m-file. you can examine any variables in the function’s workspace. In particular. you can move the mouse over the variable name in the window and its description and value(s) will be shown. Thus. 0 s 0 ). doc will give you complete details. you are still in the workspace so many MATLAB commands can still be executed.) Also. For ex- ample. you are running the debugger — and it is running your program. In addition. to see the values of variables just type the variable name into the workspace. 105 . Function M-files pause into your code and wonder why it is taking so long to execute. type >> echo <function name> on and to turn echoing on for all functions. or in a MATLAB window you can use the mouse and click on the commands. you can also change the value of any of these variables. especially when if state- ments are involved. (Alternatively. but only provide a brief description of each one. However. The alternative input( 0 Press Enter to continue 0 .3. The only way you will recognize this is not a “standard” MATLAB session is that the prompt is K>> for Keyboard. this does not affect function files. and echo off turns echoing off again. If you have experience with using a debugger. because these are similar to commands in any debugger. to distinguish these commands from “normal” MATLAB commands they begin with db. pauses the code and also reminds you that it has been paused. similar to the pause command. you can run most MATLAB commands as long as you do not try to create new variables (but you can modify existing variables). type >> echo on all The keyboard command is also very useful for debugging m-files. The echo command is also useful for debugging script and function m-files. We will not discuss the commands in this debugger in detail. it returns complete control to the user to enter any and all MATLAB commands. enter K>> dbquit When using the debugger. Typing >> echo on turns on the echoing of statements in all script files (but not printing the results if the statements end with semicolons). 8. To turn echoing on for a particular function. enter K>> return To terminate both the “keyboard” session and the execution of the m-file. you are not running your program. However. Instead. To terminate the “keyboard” session and return control to the m-file. many of the commands you enter are commands for the debugger. If de- sired.

3. the calling statement might be any of the following: >> art = funct2(1. dbup Change the workspace to the calling function or the base workspace. then a vector. 3 4] It is particularly important to understand this “typelessness” when considering output arguments. dbdown Change the workspace down to the called function. b. For example. there are three output arguments to funct2 and any of them can contain any type of variable. each of which can be any type of variable. t) a and t are the input arguments and out is the output argument. a double-precision floating-point number. For example. There is no requirement that all three of these output arguments actually be used. dbstep Execute the next executable line. In MATLAB. chemistry] = funct2([1 2 3]) >> [math. Function M-files Debugging Commands keyboard Turns debugging on. For example. a single-precision floating-point number. In fact. 6. 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. as we discuss at the end of this section. in funct2 if z is modified and returned in out1 then the calling sequence should be >> [z. a character string. this is not usually a good idea. For example. out3] = funct2(z) z is the only input argument and there are three output arguments. horticulture] = funct2(reshape([1:30]. dbstep n Execute the next n lines. dbstep in The same as dbstep except that it will step into another m-file (rather than over it). >> x = 0 WOW? 0 >> x = x + 0 >> x = sum(x) >> x = x*[1 2. philosophy. a variable might be an integer. For ex- ample. dbclear Remove a breakpoint. 8. the following statements can follow one another in order and define x to be a string variable. dbcont Continue execution. That is.) In function [out1.5) >> [physics. For example. there is no such requirement. including the line numbers. Now we want to discuss the arguments in a MATLAB function. dbtype List the current function. 5)) (just to be somewhat silly). in function out = funct1(a. (This is true no matter what type of variables they are. on the other hand. in MATLAB input arguments occur on the right side of the equal sign and output arguments occur on the left. dbstop Set a breakpoint. you can let the type of these arguments depend on the value or type of the input argument. etc. return Quit debugging mode and continue execution of the function. (There is an alternative to this awkward use of param- eters which are modified by the function: you can make a variable global. dbquit Quit debugging mode and terminate the function.) There is another difference between MATLAB and most other programming languages where the type of each variables has to be declared. This is 106 . since they are are used somewhat differ- ently than in other programming languages. However. this also works in script m-files. out2. dbstep out Executes the remainder of the current function and stops afterwards. c] = funct2(z) where z appears on both sides of the equal sign. either explicitly or implicitly. dbstatus List all the breakpoints. and finally a matrix. Arguments which are to be modified by the function must occur on both sides of the equal sign in the calling statement. then a scalar. dbstack Display all the calling functions.

8. MATLAB also has global variables which are defined by declaring the variables to be global using >> global <variable 1> <variable 2> <variable 3> . param) alpha = param. this may be desirable if a variable is modified by a function.) To make this last function easier to read we could write it as function z = fncz3(y. There are many reasons why evaluating h(y) using fncz1. For each experiment these parameters will be fixed. We can always simplify this function by combining the four parameters into one structure by function z = fncz2(y. Note: The first time you enter the function. but it is sometimes very useful. Warning: Spaces. this is done by declaring the variable static. param) z = [ y(2) .. you must type this statement (or be put into a script file which you execute) before these variables are used. Normally.. which we have written.omega z = [ y(2) .alpha beta = param.Gamma*cos(param. a variable is a global variable if it appears in a global statement and a local variable if it does not. Gamma. 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. Suppose we want to write a function m-file to evaluate y2 h(y) = y1 (1 − βy12 ) − αy2 + Γ cos ωt where α. beta.Gamma omega = param. and ω are parameters which will be set initially and then left unchanged during a run.3. -y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ]. (The parameter Gamma is capitalized even though it is not a matrix because γ is very different from Γ. fncz2. omega) z = [ y(2) . We now present a simple example where persistent variables are very helpful. this function might be called repeatedly inside a general purpose func- tion m-file. param. say general. Occasionally. not commas. In C.e. For instance. (Note that a variable can be a local variable in one function and a global variable in another. We do not want to “hardcode” the values in the function because we would have to repeatedly change the function — which is very undesirable. but they will be different for each experiment. ˆ but then we have to include these four parameters in each call to the function. many times for different values of y.) In C this is done by using global variables... or fncz3 might not be desirable — or even practical.) This statement must appear in every function which is to share the variables. (If this function was more complicated it would be much harder to read. In general we only want to call the function as z = fncz?(y) and not have to worry about how parameters are passed to the function. a persistent variable will be empty. ˆ but then it is harder to read the equation. -y(1)*(1-param. 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. -y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ]. (As we discussed earlier. Function M-files probably not something you should want to do frequently. must separate the variables in a global statement Instead of using a global variable... it is frequently preferable to save the value of a local variable between calls to the function.) We might be studying a mathematical model where this function will be evaluated many.. Warning: Spaces. If the workspace is also to share these variables. By the way. []. local variables come into existence when the function is called and dis- appear when the function ends. i.alpha*y(2)+. and you can test for this by using isempty. must separate the variables. alpha.beta Gamma = param. The first way to reduce the number of parameters is to write the function m-file for h(y) as 107 . ˆ but we want to propose two other alternatives. not commas.omega*t) ]. Certainly we can write the function as function z = fncz1(y. In MATLAB it is done by declaring the variable persistent using >> persistent <variable 1> <variable 2> <variable 3> . β.beta*y(1) 2)-param. Γ.

For example. This discussion of saving parame- ters in functions has been somewhat lengthy — but it has many uses.05.) Now. Gamma p = Gamma. end z = [ y(2) . This can be annoying if a number of files have to be cre- ated: for example. (At the end of Section 10. it can be difficult to remember the purpose of all these functions. In the initial call all the parameters are saved in persistent variables. NOT varargin(k).5. omega p = omega. It frequently happens that a block of code occurs two or more times in a function. if fnc x calls the function fnc2 and passes all but the first argument. i. >> Gamma = 0. Then we can declare the function as function fnc(varargin) or. In MATLAB functions normally have to be separated into different files so that each function and its file name agree. 108 . then the call can be written as fnc2(varargin) By the way. varargin) The varargin argument. Warning: Recall that the k th argument in varargin is varargin{k}. >> fncz1 c = @(y) fncz1(y. alpha. beta p = beta. otherwise.0. and it can be difficult to debug the primary function. 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. even if possible. Another reason for splitting a block of code off into a new func- tion is when the function has grown large enough to be hard to comprehend.. fncz1 c(y) is evaluated as fncz1(y. MATLAB has a feature to handle this proliferation of files. ˆ we will initially call the function as fncz4(y. >> omega = 1. beta. especially when there can be a variable number of arguments. This argument can even be passed into another function and will be handled exactly as if each element was passed separately. The remedy is to split the code up into a number of functions. Function M-files function z = fncz4(y.2 we code the function gravity using a number of nested functions. We return to the function fncz1 and create a new function by >> alpha = 0. Gamma. The final — but very important — technical detail about function m-files concerns an important ele- ment of programming style in any computer language. It is possible to end the primary function and each subfunc- † A closure is a complicated term to explain.e. Sometimes these blocks can be combined by using a loop. Gamma. beta. this often makes the code unwieldly. >> beta = 1. The second way is to use closure† . Gamma.e. alpha. alpha. MATLAB cannot find the function. the line which begins with the keyword function ). alpha.0. if there is always at least the argument x. 8. The first function in the file is called the primary function and its name must agree with the name of the file. beta. omega) and then afterwards call it as fncz4(y). omega). omega) persistent alpha p beta p Gamma p omega p if nargin > 1 alpha p = alpha. Another technical detail concerns how to “group” input arguments and/or output arguments together. each of which can be easily understood and debugged. Gamma. For example. Later calls do not need to input these parameters because they have been saved in the function.) Note: The primary function or a subfunction begins with the function definition line (i. omega) (The “c” denotes the fact that duffing c is an anonymous function handle which is also a closure.3. beta. Instead. There are two further types of functions: Any remaining functions are called subfunctions or nested functions. function m- files can contain more than one function. suppose there can be any number of input arguments to the function fnc. this block of code can be put into a new function and called from the original function.. but. x. as function fnc x(x. -y(1)*(1-beta p*y(1) 2)-alpha p*y(2)+Gamma p*cos(omega p*t) ]. the output argument varargout is handled exactly the same on the left hand side of the function declaration statement. is a cell vector whose length (which can be 0 ) is calculated by length(varargin). which must always be the last in the argument.

Usually. Nested functions are more complicated than subfunctions and we will only provide a brief discussion. When they are not suffi- cient. 109 . First. 8. Function M-files tion with the command end. lookfor. but this is not necessary because MATLAB recognizes that a function has ended when it encounters the next function statement. However. which are quite simple. different m-files can contain subfunctions with the same name. if a nested function is used then it — and all other functions — must end with the end statement. subfunctions are sufficient — and they are much easier to describe. For example. Also. consider the following function m-file. Thus. the help. 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. They are placed following the primary function and between or following other subfunctions. The only way to pass variables between these functions is through the argument list. 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 ). 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. we have nested functions.3. and they are somewhat related to inner classes in Java — but not in C++. † They are similar to internal functions in Fortran 95.† To make this discussion specific. and type commands can only access the primary file. we discuss subfunctions.

% 5 p2 = p1 + nest 2(40). ˆ % 20 p3 = n2a. the nested functions nest 1 and nest 2 are nested within the primary function nested ex. % 2 p2 = y. a nested function can have local variables. % 10 p1 = n1a + n1b. % 14 end % 15 function out2 = nest 2(r) % 16 n2a = p1 + r. % 28 s2 = a + b. % 31 %%%%% nested function follows function out3 = nest 3(t) % 32 n3a = s1 2 + t. % 4 p1 = p1 + nest 1(20). The scope of a variable is the context within which it is defined. Function M-files function [p1. since a nested function is within one or more other functions. p3] = nested ex(x. % 19 p2 = p2 2. mod- ified. (Nested functions can have other nested functions within them. However. 8. ˆ % 21 out2 = p1 + p2. % WRONG % 18 p1 = n2a 2 + n1b. % WRONG % 30 s3 = s2 + nest 3(s1). b) % 27 s1 = 10. To begin. % 17 % p = p + p1 + p2. and used. num2str(n1b)]) % 25 end % 26 %%%%% subfunction function s3 = sub 1(a. p2). % 8 n1b = p2 + z. In the function nested ex the nested functions nest 1 (lines 7–15) and nest 2 (lines 16–23) have access to the variables p1. Note that nest 2 also has access to nest 1 as shown in line 14. % 6 %%%%% nested functions follow function out1 = nest 1(r) % 7 n1a = p1 + z + r. % 29 % s2 = s2 + p2. % 34 end ˆ % 35 % disp(out3) % WRONG % 36 end % 37 A nested function is within another function. % 33 ˆ out3 = n3a 2. and p3 of the primary function (lines 1–26). % 12 p3 = sub 1(p. z) % 1 p1 = x.) The important concept to understand when using nested functions is the scope of variables in the func- tion m-file. it is within the workspace of this function or these functions. but enough is enough.3. % 22 end % 23 disp([ 0 r = 0 . p2. i. % 13 out1 = nest 2(1). % 3 r = 5. and the nested function nest 3 is nested within the sub- function sub 1. The workspace of the primary function is also independent of the workspace of each subfunction. Any variable in the argument list of a nested func- 110 . Now let us consider a function workspace. % 9 p = p1 + p2.. p2. For example. where it can be set.e. % 11 p2 = n1a*n1b. y. num2str(r)]) % 24 disp([ 0 n1b = 0 . They also have access to the subfunction sub 1 (lines 27– 37) (but not any of its variables) as shown in line 13.

e. The functions in this subdirectory are called private functions. the variable out1 is local to the function nest 1 and out2 is local to nest 2. 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. (This could be done by adding n1a = 0 after line 3. say myrref. As we stated previously (but did not discuss). Thus. Also. suppose we are working in the directory “personal” and have created a number of files which use rref to solve linear systems.m. the variables t and out3 are local to nest 3... Simi- larly. Finally. Now let us return to the topic of how MATLAB finds a function. “ ”. FG FG FG FG lution is to append a special character to all local variables in nested functions FG FG FG FG (for example. For instance. and to change the call to rref in every file in this directory to myrref. i. append an underscore. MATLAB first checks if the function named is the primary function or a subfunction in the current file. n1a cannot be accessed in nest 2 as shown in line 17. One so. Because of the way that MATLAB searches for functions. It is possible — and sometimes useful — for a † Since MATLAB contains thousands of functions. improved version”. the variables p1 and p2 are defined in nested ex and so can be used in nest 1 and nest 2.) On the other hand. The final topic we will briefly discuss involves recursion. we can code and debug our new function in the subdirectory “private”. 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. Similarly. This would be quite time-consuming. FG FG FG FG FG FHDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDHG @EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEA Just for completeness. the variable r is local to nest 1 and also local to nest 2. Instead. Any m-files in this subdirectory are visible only to functions in the current directory. i. Function M-files tion is local to that function. none of the variables in nested ex can be accessed in sub 1 and vice versa. then it must be in the workspace of nested ex. For example. Also. MATLAB searches for the m-file in the current directory. All calls in the directory to rref will use the new function we are testing in the subdirectory “private”. Only if all this fails does MATLAB use your search path to find the function. This is also true for p3 which is an output variable in nested ex. rather than MATLAB’s function. note that n1b is not used in nested ex until line 25. nested ex does not define or use them. The variable r which is defined on line 4 is unchanged by the calls to the two nested function. when breaking a function up into a primary function plus subfunctions. and the same is true for any variable which contains values returned by the function. 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. The value returned in line 24 will always be 5. When you think up a name for a primary function (and. it would be very annoying if the name of every subfunction had to be checked — especially since these subfunctions are not visible outside the m-file. more general. this means you do not have to worry about one of your sub- functions being “hijacked” by an already existing function. 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 local variable in a nested function and forgetting that the same variable name FG FG FG FG is used in the outer function. way to handle this replacement: you can create a sub- directory in your current directory with the special name “private”. The usual way to test our new function would be to give it a new name. and we might well miss some. 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. p2 cannot be accessed in the subfunction sub 1 as we show on line 30. (If n1a really needs to be passed to nest 2. However. Even more important. for the name of the m-file) it is important to check that the name is not already in use. If it is not. 111 . when a function is called from within an m-file. because we think we can calculate the reduced row echelon of a matrix more accurately.3. to the end of the name of each local FG FG variable). any function in any other directory which calls rref will use the MATLAB function and not our “new.e. n3a is local to nest 3. 8. Then MATLAB searches for a private function by the same name (described below). thus. And suppose we have written our own version of this com- mand. There is another. letting the name of our new function be rref and the name of the m-file be rref.

55. . nargout Number of output arguments supplied by the user. % no recursion if n = 1 else y = fibonacci(n-1) + fibonacci(n-2). i. it can be shared between different functions and/or the workspace).. addpath Add directories to the current search path. 112 . can be coded as function y = fibonacci(n) % WARNING: VERY VERY INEFFICIENT CODE % ***** n must be a nonnegative integer ***** if n == 0 y = 1. 13. This sequence. 1. This statement is only required if the function m-file con- tains a nested function. global Defines a global variable (i. echo Turns echoing of statements in m-files on and off. in which case it must be used by all the functions in the file. return Terminates the function or the script m-file immediately.. 34. Function Commands function Begins a MATLAB function. Function M-files function to call itself. However. error( 0 <message> 0 ) Displays the error message on the screen and terminates the m-file immediately. 8. . % no recursion if n = 0 elseif n == 1 y = 1. 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. 3.e. % two recursive calls for n > 1 end A recursive code must be able to stop. Where to Search for Functions path View or change the search path. Warning: This code is very. very. As a simple example. varargout “Groups” output arguments together. very. 2. For larger values of n. 89.e. end Ends a function. in order to calculate fn the function fibonacci is called recursively 2fn − 2 times — and fn grows exponentially with n. varargin “Groups” input arguments together. 5. very large). consider the Fibonacci sequence fn+2 = fn+1 + fn for n ≥ 0 with initial values f0 = 1 and f1 = 1 . and this code stops if n = 0 or n = 1. There are examples for which recursion is advantageous. nargin Number of input arguments supplied by the user. 21.3. 1. very inefficient. We have provided it simply to show how recursion can lead to a very compact code. our aim is simply to show how to use it — not whether to use it. 8. persistent Defines a local variable whose value is to be saved between calls to the function.. . In fact. the function is called recursively. pause Halts execution until you press some key.

xn are the arguments to the function. recall that s is really just a row vector with each element containing the ASCII repre- sentation of the corresponding character. >> c2=H(:. then c2=H(:. (To understand how s is created.6) >> A = feval( 0 zeros 0 . 5. xn) (See below for other ways to pass the function in the argument list.) Here x1. There is a very practical applications for this command since it can combine a number of statements into one.1). >> [m. 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. n).) If there is an error. x2. plot(x. if it fails then the contents of <catch string> are executed. y = x. say sample.i). whose name is contained in a string by >> feval(<string>. 0 =H(:. the following two statements are equivalent >> A = zeros(5. To use this feature of eval. . then m is 5 and n is 6. n] = eval( 0 size(A) 0 ). which gets tiring very quickly. In addition. We can input the type of plot to use by 113 .2).. this is the output of eval. y) 0 >> eval(s) executes all three statements contained in the string s. Instead.*sin(x).. 6) Suppose that in the body of one function. (This might be a call to a function which can handle the error. the command lasterr returns a string containing the error message generated by MATLAB. .i) 0 ] ) end This requires some explanation.*exp(x/5). etc.6). <catch string>) The function executes the contents of <try string> and ignores the second argument if the execution succeeds.2) the second time. x2. we can do this by typing >> for i = 1:n eval( [ 0 c 0 num2str(i) 0 =H(:. For example..) Finally.. suppose in function sample we want to generate either linear or logarithmic plots. usu- ally defined by an m-file.. entering >> s = 0 x = linspace(0. For example. we want to execute another function whose name we do not know.. . if an executed statement generates output. Odds and Ends 8. s is a text variable which contains c1=H(:.4. as the pro- gram is running.. there is a very esoteric application for this command that allows it to catch errors. x1.. A MATLAB command which is occasionally useful in a function is feval. rather than using H(:. num2str(i). if we type >> A = zeros(5.e. 10. This is sim- ilar to the “catch” and “throw” commands in C++ and Java. For example. We can do this by hand by typing >> c1=H(:. 8. Then feval can be used to execute this text variable. Entering >> eval(<string>) executes whatever statement or statements are contained in the string. i.4. For example. It executes a function. call it using two arguments as >> eval(<try string>. It might be a little clearer if we separate the statement inside the for loop into two statements by s = [ 0 c 0 . For example.. Instead. the name of the function is to be passed as an argument to sample.i) 0 ] eval(s) (where we include commas in the first statement for readability).1) the first time the loop is executed. However. Odds and Ends In MATLAB it is possible for a program to create or modify statemennts “on the fly”.

longer than the time you think it will take before you get started.6) 0 ). feval is much more efficient. feval( 0 loglog 0 .. x. consider the function hilb on page 102.0 . There are two common ways to pass the function <type of plot> in the argument list: (1) use a character string. stifle the urge to muck around with it.. if your code is executing “slowly”. 0 feval(<type of plot>. (Can be used to pass a function name by argument. † We have put “quickly” and “slowly” in quotes because this is quite subjective. Of course. As a simple example of method (0). then it has been written in C and is faster than anything you can do. or (2) use a function handle.g. y3. . feval Executes a function specified by a string.). If a MATLAB function is built-in. y1... it is contained here. much time has been spent optimizing the functions that come with MATLAB. especially if the string must be evaluated many times inside a loop. Remember that your time is valuable: if it takes you longer to optimize your code than you will save in running it more quickly. feval(@logval. for example. However.) lasterr If eval “catches” an error. However. In fact... you might be willing to spend some time trying to speed it up..5. whenever possible.† There are three standard methods to speed up a code: (0) Preallocate matrices as shown in the function prealloc on page 102. hilb local(2000) runs over 300 times slower if the line H = zeros(n) is omitted. 114 . xx.). Odds and Ends eval Executes MATLAB statements contained in a text variable. or Note: eval and feval serve similar purposes since they both evaluate something. y2.. you are unlikely to do better.g. Advanced Topic: Vectorizing Code function sample(<type of plot>) . . whereas feval only requires MATLAB to evaluate an already existing function.. e.. -. e.... 5. there is a fundamental difference between them: eval requires the MATLAB interpreter to completely evaluate the string. . >> profile viewer begin and end profiling and display the results in the Profiler window. (2) Replace flow control instructions with vector operations. rather than writing your own. Here we will focus on some advanced techniques. Also remember that the amount of time it actually takes to optimize a code is usually a factor of two or three or .5... feval( 0 zeros 0 . 8. feval can always be replaced by eval since. Advanced Topic: Vectorizing Code As long as your MATLAB code executes “quickly”. We have already discussed this topic at length in Section 8. 8.. 0 :0 ) . x. Even if it is not. we should first determine how much CPU time is really being expended in our program — and that is the profile command. This is very simple and very effective if the matrices are “large”. (1) Use MATLAB functions. . 6) can always be replaced by eval( 0 zeros(5. 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 commands >> profile on >> .2... Can also “catch” an error in a statement and try to fix it. there is no need to try to make it faster..

. now hilb local they are “roughly” comparable — depending on the computer and operating system. Thus. What is the average length of these intervals and what is their standard devia- tion? Also. 1). % J is a row vector J = J(ones(n. ignore any intervals which begin or end y ). % I is an n by n matrix with each column being 1:n E = ones(n.5. In particular. consider the inter- vals in y where yi > R. It is not difficult to write such a code using flow control statements: 115 . as can be seen by entering >> edit hilb In the past this code ran nearly 20 times as fast as hilb local. The reason is that MATLAB has greatly improved its handling of for and while statements. 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. currently the MATLAB function hilb is written as function H = hilb2(n) J = 1:n. it is frequently not necessary to convert simple loops into complicated vector code. 8. n). However. only include intervals which lie completely within y (i. H = E.e. % J is now an n by n matrix with each row being 1:n I = J0 .:)./(I+J-1). Advanced Topic: Vectorizing Code Continuing with this example.

Here is the code: 116 . yin and yout contain the element numbers where an interval begins and where it ends. so delete it yout(1) = []. This is straightforward — but very slow if y has millions of elements. % yes intvl nr = 1. in intvl = 1. (2) We do not actually care about the 0’s and 1’s — only about where the value changes because these mark the boundaries of the intervals. respectively. end for i = [2: n] % check the rest of the points if in intvl == 1 % we are currently in an interval if y(i) <= R % check if this point is also in the interval yout(intvl nr) = i. 8. only the lengths of these intervals. So we take the difference between adjacent elements of yr by yd = diff(yr). So we take every other element of ylen. When completed. To write a vectorized code. So we construct a logical matrix corresponding to y by yr = (y > R). else in intvl = 0. % no.. end else % we are currently not in an interval if y(i) > R % check if this point is in the next interval intvl nr = intvl nr + 1. end if length(yin) > length(yout) % check if we have ended in an interval yin( length(yin) ) = []. ylen contains the lengths of both the intervals and the distances between successive inter- vals. ˜ (4) We do not care about the actual locations of the beginning and end of each interval. we have to think about the problem differently: (1) We do not care about the actual values in y.5. (3) We actually only need to know the elements which contain nonzero values so we find the element numbers by ye = find(yd). end end end if y(1) > R % check if we have begun in an interval yin(1) = []. R) n = length(y). So we take the difference again by ylen = diff(ye). so begin a new interval yin(intvl nr) = i. ye = find(yd =0). (5) Finally. We also have to be a little careful and check whether y begins and/or ends in an interval. so end the interval in intvl = 0.e. if y(1) > R % check if the first point is in an interval in intvl = 1. yin(intvl nr) = 1. % yes. so delete it end ylen intvl = yout .yin. % yes. i. % no intvl nr = 0. Advanced Topic: Vectorizing Code function ylen intvl = get intervals slow(y. only whether they are greater than R or not. % yes.

9. Sparse Matrices

**function ylen intvl = get intervals fast(y, R)
**

yr = (y > R); % (1)

yd = diff(yr); % (2)

ye = find(yd); % (3)

ylen = diff(ye); % (4)

if y(1) > R % (5), check if we begin in an interval

ylen(1) = []; % yes

end

ylen intvl = ylen( 1:2:length(ylen) ); % get every other length

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.

Improving Efficiency of Function

**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 ∈ Cn×n is a tridiagonal matrix, then the maximum number of nonzero elements is 3n−2. 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 commands needed to work with sparse matrices. However, there are a

number of commands which are inappropriate for sparse matrices, and MATLAB generally generates a

warning message and refers you to more appropriate commands. For example, cond(S) has to calculate

S−1 , 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 command; or, second, use the recommended alternative command.

There are three common commands 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 ∈ Cm×n 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

n−1 −4 0

n−2 −6

S= .. ..

. .

2 −2n + 2

0 1

117

9. Sparse Matrices

has the following nonzero elements

i j si,j i j si,j

1 1 n 1 2 −2

2 2 n−1 2 3 −4

3 3 n−2 3 4 −6

.. .. .. .. .. ..

. . . . . .

n−1 n−1 2 n−2 n−1 −2n + 4

n n 1 n−1 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 command, but it would be more complicated. The

above command is easier to understand, even if it does require adding two sparse matrices. Since the out-

put from this command 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 m×n matrix can be generated by

>> SZ = sparse(m, n)

which is short for

>> SZ = sparse([], [], [], m, n)

The third common command 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 command 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)

118

9. Sparse Matrices

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

is not used since it would go into the element sn,n+1 .

A slight variation of the above command is

>> T = spdiags(B, d, S)

where T is equated to S and then the columns of B are placed in the diagonals of T specified by d.

Thus, a third way to generate the matrix S given above is

>> S = spdiags([n:-1:1] 0 , [0], n, n)

>> S = spdiags([0:-2:-2*n+2] 0 , [1], S)

Just as with the diag command, we can also extract the diagonals of a sparse matrix by using

spdiags. For example, to extract the main diagonal of S, enter

>> B = spdiags(S, [0])

The number of nonzero elements in the sparse matrix S are calculated by

>> nnz(S)

(Note that this is not necessarily the number of elements stored in S because all these elements are

checked to see if they are nonzero.) The locations and values of the nonzero elements can be obtained

by

>> [iA, jA, valueA] = find(A)

The locations of the nonzero elements is shown in the graphics window by entering

>> spy(S)

These locations are returned as dots in a rectangular box representing the matrix which shows any struc-

ture in their positions.

All of MATLAB’s intrinsic arithmetic and logical operations can be applied to sparse matrices as well

as full ones. In addition, sparse and full matrices can be mixed together. The type of the resulting matrix

depends on the particular operation which is performed, although usually the result is a full matrix. In

addition, intrinsic MATLAB functions often preserve sparseness.

You can generate sparse random patrices by sprand and sparse, normally distributed random matri-

ces by sprandn. There are a number of different arguments for these functions. For example, you can

generate a random matrix with the same sparsity structure as S by

>> sprand(S)

or you can generate an m×n matrix with the number of nonzero random elements being approximately

ρmn by

>> sprand(m, n, rho)

Finally, you can generate sparse random symmetric matrices by sprandsym; if desired, the ma-

trix will also be positive definite. (There is no equivalent command for non-sparse matrices so use

full(sprandsym(...))

Additionally, sparse matrices can be input from a data file with the spconvert command. Use

csvread or load to input the sparsity pattern from a data file into the matrix <sparsity matrix>.

This data file should contain three columns: the first two columns contain the row and column indices of

the nonzero elements, and the third column contains the corresponding values. Then type

>> S = spconvert(<sparsity matrix>)

to generate the sparse matrix S. Note that the size of S is determined from the maximum row and the

maximum column given in <sparsity matrix>. If this is not the size desired, one row in the data file

should be “ m n 0” where the desired size of S is m×n. (This element will not be used, since its value is

zero, but the size of the matrix will be adjusted.)

119

We also provide a large number of ex- amples. β. 10. and ω. full Converts a sparse matrix to a full matrix. sprandsym Generates a sparse uniformly distributed symmetric random ma- trix. Thus. Instead. spfun( 0 <function name> 0 . Basic Commands Sparse Matrix Functions speye Generates a sparse identity matrix.1. spy Plots the locations of the nonzero elements of a matrix. many more than in other sections of this overview. find Finds the indices of the nonzero elements of a matrix. sprand Sparse uniformly distributed random symmetric matrix. As written. 10. The basic MATLAB commands are easily learned. How- ever. This ode has many different types of behavior depending on the values of the parameters α. Initial-Value Ordinary Differential Equations Most initial-value ordinary differential equations cannot be solved analytically. 10. spdiags Generates a sparse matrix by diagonals or extracts some diagonals of a sparse matrix. the matrix can also be positive definite. using MATLAB we can obtain a numerical approximation to the ode system d y = f(t. the ma- trix can also be positive definite. A) Applies the function to the nonzero elements of A. this is not in the form of a first-order system. sprandn Sparse normally distributed random matrix. Basic Commands In this subsection we focus on the particular example y 00 + αy 0 − y(1 − βy 2 ) = Γ cos ωt . which is called Duffing’s equation. we divide this section into the really basic commands which are needed to generate a simple trajectory and into a more advanced section that goes into many technical details. to provide a template of how to actually use the advanced features. The arguments are the same as for eye. y) for t ≥ t0 dt where y ∈ Rn with initial condition y(t0 ) = y0 . sparse Generates a sparse matrix elementwise. y2 y1 (1 − βy12 ) − αy2 + Γ cos ωt 120 . 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 = . the commands become more involved if we want to explore the trajectories in more detail. nnz Returns the number of nonzero elements in a matrix.1. Γ. spconvert Generates a sparse matrix given the nonzero elements and their indices.

The circles on the trajectories show the actual times at which the solu- tion is calculated. All of the solvers use the same input and output arguments.e.1. y0) or >> [t. However. . Y] is unrelated to the t argument in the function duffing. tspan The vector that specifies the time interval over which the solution is to be calculated. etc. AbsTol(i) } where the default value of RelTol is 10−3 and of the vector AbsTol is 10−6 for each element. 0 yn = yn−1 . Before discussing how to solve Duffing’s equation specifically.† Y The matrix which contains the numerical solution at the times corresponding to t. ‡ We have capitalized the Y in [t. If this vector contains two elements. y2 (t). tspan. 10. these are the initial time and the final time. .. and we also briefly discuss it below. y2 = y10 . y1 (t). as shown in the table below. which is the error in yi . ei . If there are no output parameters. yn (t). . these are the only times at which the solution is output.y The matrix which contains the numerical solution at the times corresponding to t. Y] to indicate that the output is a matrix whereas the argument y is a vector in the function. . y0) First.x The column vector of the times at which the solution is calculated. these are: t The column vector of the times at which the solution is calculated. then it is a structure. That is. enter >> <ode solver>(<function handle>. 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). the individual elements of the solution. t on a single plot. (How- ever. y0 The vector of the initial conditions for the ode.) † The t in [t. there is no guarantee that the error in the numerical calculation actually satisfies this bound. sol. y3 = y20 . Basic Commands Note: This same “trick” can be applied to an nth order by defining y1 = y.2. The output is now sol. Note: the final time can be less than the initial time. 121 .‡ If there is one output parameter. tspan. There are seven distinct ode solvers which can be used. we discuss the commands which solve time-evolution odes. this is discussed in detail shortly. are plotted vs. tspan. The input parame- ters are: function The name of the function handle that calculates f(t. Y] = <ode solver>(<function handle>. All these ode solvers use an adaptive step size to control the error in the numerical solution. is supposed to satisfy ei ≤ max{ RelTol · |yi |. . i. To obtain a numerical solution to a time-evolution first-order ode system. The first column of Y contains y1 . y). there are good reasons why the decision should be left in the hand of the user. in this case the ode solver determines the times at which the solution is output. If there are two output parameters. y0) or >> sol = <ode solver>(<function handle>. Warning: Make sure you understand how to enter the name of the function handle. we have to choose which ode solver to use. . It would be possible for MATLAB itself to decide which numerical method to employ. which we now discuss. . This is discussed at length in Section 3. . If this vector contains more than two elements. the second column y2 . in which case the trajectory is moving backwards in time.

we say it is stiff if the time step re- quired to obtain a stable and accurate solution is “unreasonably” small. ode23t Stiff ode solver. (Which one runs faster is very dependent on the ode..e. ode23 Non-stiff ode solver. The above examples are very simple. 10.e. consider the ode y 00 − 1001y 0 + 1000y = 0 whose solution is y(t) = c1 et + c2 e1000t . one-step method. ode23s Stiff ode solver.e. one-step method. Instead. variable-order. second-order.. The solution to this ode is y(t) = c1 et + c2 e−1000t where 1 1 c1 = (η1 − η2 ) and c2 = (1000η1 + η2 ) . However. 1001 1001 There are two time scales in this solution: there is a rapid decay due to the e−1000t term and there is a slow growth due to the et term. this is not a stiff ode. ode113 Non-stiff ode solver. That is. And what is a stiff ode? There is no precise definition. one-step method. trapezoidal method. multi-step method. second-order. second-order. Basic Commands ODE Solvers ode45 Non-stiff ode solver. ∆t 1/1000 ). one-step method. soon it will be negligible and the time step should increase so that it calculates the slowly decaying mode accurately (i. then try ode15s.e. the time step will be “very small” so that the rapid decay is calculated accurately (i. Consider the second-order time-evolution ode y 00 + 999y 0 + 1000y = 0 for t ≥ 0 with the initial conditions y(0) = η1 and y 0 (0) = η2 . or if these two non-stiff solvers fail. the time step will be “very small” so that the rapid decay is calculated accurately (i. fourth-order.e. However. try ode45 or ode113. The best way to explain this rather vague impression is through some simple examples.. where some reactions occur on a very fast time scale and 122 . However.1. the time step must always be “very small”. if a stiff solver is used. these methods should run “reasonably fast”. ∆t 1 ). It is up to you to decide which ode solver to use. the time step can increase by many orders of magnitude when the rapidly decaying term has disappeared. soon it will be negligible and the time step should in- crease so that it calculates the slow growth accurately (i. On the other hand. The reason is that a numerical instability will cause the trajectory to blow up if the time step increases..) If you know (or believe) that the ode is stiff. variable-order. For a given level of accuracy. The same is true for the ode y 00 + 1001y 0 + 1000y = 0 whose solution is y(t) = c1 e−t + c2 e−1000t . ode15s Stiff ode solver. However. 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. ∆t 1 ). the time step must always be “very small” so that the rapidly growing mode e1000t is calculated accu- rately (i. Initially. ∆t 1/1000 ). unless you believe that the ode is stiff (which we discuss in the next paragraph). ode23tb Stiff ode solver. (This fre- quently happens in chemical reaction models. Initially. it must accurately track the rapidly decaying term — even after this term has disappeared in the numerical solution. As a general rule. Thus.. ∆t 1/1000 ). is used. multi-step method. if a non-stiff solver. such as ode45 or ode23.

>> beta = 1. The next simplest approach is to use a nested function. This is easily accomplished by changing the last line of the previous code to >> [t. 1) >> plot(t. which is called a phase plane. Since this is a very well-behaved ode for the parameters given. function duffing ode(alpha. y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ]. 2) >> plot(t. >> figure(1) >> subplot(2.1. y) deriv = [ y(2) . The simplest approach is to use an anonymous function to input the right-hand side.5. You may have to calculate all these partial derivatives yourself and include them in your function file. [2 1]). if the ode is “bad” enough. 1. so that both plots are visible even if they have vastly different scales. not only is the trajectory plotted. t. final time) ode45(@duffing n. [0 100].2)) >> figure(2) >> plot(Y(:. (This plot is rather “cluttered” because. y) is the n×n matrix ∂fi J(t. will succeed. Y(:. Suppose we want to solve the ode for t ∈ [0. %%%%% nested function follows function deriv = duffing n(t. and so there must also be a primary function. [2 1]). You can plot the solution and observe the separation of the fast scale and the slow scale as this parameter increases. y)[y(2) . >> omega = 1. Y] = ode45(duffing a.2)) This results in a plot of y vs. To obtain complete control over what is plotted. a second-order ode which is either non-stiff or stiff depending on the value of one parameter.0.) The solution will now be plotted as y1 and y2 vs. ∂yj i. y) . the function handle duffing a will always use these parameters. 10. ∂yj Any of the stiff methods can approximate this matrix numerically. Also. 100] with initial conditions y = (2. It is possible that most of the ode solvers will fail and only one. even if they are later changed. However.) The reason for this large choice of ode solvers is that some odes are very. y) = (t. very. (We show an example of this later. Gamma. [0 final time]. but in addition markers are put at each of the points of the numerical solution. you should let ode45 output the trajectory and do the plots yourself.1)) >> subplot(2. >> duffing a = @(t. Y(:. Note: Since duffing a is already a function handle.0. >> alpha = 0. this may not be enough.e. 1)T and plot the results..) In the next subsection we discuss van der Pol’s equation.) Note that the parameters are input to 123 . SAY MORE??? To conclude this subsection. y0). y. >> Gamma = 0. [0 100].05. >> ode45(duffing a. the element in the ith row and j th column of J is ∂fi . end ˆ end (The “n” denotes the fact that duffing n is a nested function. 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. omega. or maybe two.1). There is also a separate plot of y 0 vs. t and a separate plot of y 0 vs. beta. Y(:. t. we merely need to use its name as the first argument to ode45. 1. we return to Duffing’s equation.) Warning: There are a number of parameters which are needed by the function and these must be de- fined before the function is created. we can use ode45. y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t)]. ˆ (The “a” denotes the fact that duffing a is an anonymous function handle. Basic Commands and other occur on a much slower time scale. very nasty. y0.

ode45 thinks it is only passing two arguments to duffing c. but it is actually passing six arguments to duffing p2. To see a sampling of the different type of behavior in Duffing’s equation.3 cos t term. deriv = [ y(2) .0. After a short initial transient. y.05. 0)T the behavior appears to be chaotic. primary function alpha = 0. y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ]. to separate the initial transient behavior from the long-time behavior. Clearly. If the right-hand side is more complicated. primary function % with coefficients passed through the argument list deriv = [ y(2) . it is very inconvenient that the parameters in Duffing’s equation are determined in the function itself. omega = 1. [0 100]. function deriv = duffing p(t. But the function it invokes is duffing p2 which takes six arguments. Note: Since duffing n is a function.15. a primary function) which calculates the right hand side of this ode system. to the accuracy of the computer it is exactly periodic. Here is an example of a ode which has periodic motion for one initial condition and is chaotic for another! If we now change α from 0. then a nested function is the simplest choice. beta. Thus. This is a very bad approach because this file will have to be repeatedly modified. ˆ (The “p2” denotes the fact that duffing p2 is another primary function. the first approach only works if the right-hand side can be defined using one MAT- LAB statement. and not a function handle.22 we find periodic motion with a period of 6π.0. y) duffing p2(t. this second ap- proach (of using a nested function) requires more coding that the first approach (of using an anonymous function). alpha.) How- ever. even at t = 1000.5. approach is to create a separate function m-file (i. (This is not only true for esthetic reasons.) However.) Note that all the parameters are de- fined in the m-file so that it will have to be modified whenever we want to modify the parameters. Gamma. omega) % duffing p2: Duffing’s equation.0.e. the solution set- tles down and appears to be “regular” by t = 100: in fact. and let the initial condition be y(0) = (0. [2 1]). ˆ (The “p” denotes the fact that duffing p is a primary function. beta = 1. this function cannot be called directly by the ode solver. beta. Gamma = 0. y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ]. However. Gamma = 0. ode45(duffing c. duffing c = @(t. The third. We should be able to “explore” the rich behavior of Duffing’s equation without having to constantly modify the function — in fact. β = 1.15 to 0. we have to include ”@” before the name of the function. if we merely change the initial condition to y = (1. (which is contained in the accompanying zip file). you can use the script m-file 124 . function deriv = duffing p2(t. it appears to be exactly periodic with a period of 2π due to the 0.5. we have to include ”@” before the name of the function. Note: Since duffing p is a function..1. 1)T . By the way. Basic Commands the primary function and so are immediately accessible to the nested function. y. and oldest. Gamma. let α = 0. Finally. omega = 1. Γ = 0. (In fact. omega). and not a function handle.0. alpha. Notice that the function duffing c takes only two arguments: t and y. This is just a sampling of the behavior of Duffing’s equation in different parameter regions.3 and ω = 1. y) % duffing p: Duffing’s equation. once we have the function exactly as we want it. the more we fool around with the function. the more likely we are to screw it up!) This is easily done by adding parameters to the function file. we should never touch it again. Instead it is called indirectly using closure by %%%%% script m-file: duffing closure alpha = 0.05. beta = 1. 10.

1).. [t(l t) final time]. Advanced Commands initial time = ??? final time = ??? y0 = ??? alpha = ???. beta = ???. y)[ y(2) .2)) l t = length(t).1). Y(:. duffing a = @(t. You include these parameters in the ode solver by adding this variable to the argument list of the ode solver function as >> [t. To determine all the parameters.:)). . The result of this command is that the parameters are contained in the variable params. their possible values and the default value.2. <Value 2>. [t. Y(:. <Value 1>. params) Some of the more common parameters are shown in the table below.2)) 10. Y] = <ode solver>(<function handle>. 0 <Prop 2> 0 . y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ]. y0.) where each parameter has a particular name and it is followed by the desired value. they will be discussed further later. [0 initial time].2. 10. figure(2) plot(Y(:. Advanced Commands There are a number of parameters that we can use to “tune” the particular ode solver we choose. Gamma = ???. y0). [t. ˆ figure(1) plot(Y(:. Y] = ode45(duffing a. Y(l t. The MATLAB function odeset is used to change these parameters from their default values by >> params = odeset( 0 <Prop 1> 0 . Y] = ode45(duffing c.. tspan. enter >> odeset 125 . omega = ???.

Refine Refines the times which are output in t. 4 for ode45.e-6).. i.3). For example. .. y) was eval- uated will be printed on the terminal. OutputSel A vector containing the components of Y which are to be passed to the function speci- fied by the OutputFcn parameter. Y] = ode45(duffing a. y2 vs. For example. 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. 1. y2 . Y(:. y2 .2) vs.e. The trajectory will be more accurate — but the command will run slower. AbsTol The absolute error tolerance. >> [t..) Events A handle to a function which determines when an event occurs. JPattern A sparse matrix whose nonzero elements (which should be 1 ) correspond to the possi- ble nonzero elements of the Jacobian.2. these are passed to the ode solver when it is <Value 1>. . tspan. That is. 0 odephas3 0 which generates a plot of y1 vs.. Enter >> ballode to see a simple example. Useful MATLAB functions are: 0 odeplot 0 which generates a plot of time versus all the components of the trajectory. 0 odephas2 0 which generates a plot of y1 vs.5. and the number of times f(t.) executed. Advanced Commands Initial-Value ODE Solver Parameters odeset( 0 <Prop 1> 0 . (Default value: 10−3 ). >> [t. i. y0. If you also want the statistics on the performance of the particular ode solver used. enter >> params = odeset( 0 RelTol 0 . .) For example. y3 . t vs. . 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 ). Y(:. a plot of the trajectory can be generated automatically as it is being calculated. params). enter >> params = odeset( 0 RelTol 0 . if we are calculating the motion of the earth around the sun. we can end the calculation when the ball hits the ground — or we can let it continue bouncing. 0 on 0 ). if you want to use ode45 with the relative error tolerance set to 10−6 for Duffing’s equa- tion. suppose we want to record where and when a trajectory of Duffing’s equation passes through y1 = ±0. OutputFcn A handle to a function which is called after each successful time step. tspan. and the number of times the linear system was solved will also be returned. if we are following the motion of a ball. The ode solver can also record the time and the location when the trajectory satisfies a particular con- dition: this is called an event. Y(:. 1.2). Y(:.1) vs.) RelTol The relative error tolerance. the number of failed steps. 0 Stats 0 . the number of times the Jacobian was evaluated. . the number of LU decompositions.e. This integer value increases the number of times by this factor. Y(:. This can be done by modifying the primary function duffing ode and replac- 126 . For implicit methods where the Jacobian needs to be calculated.. params).e. For example. i.5 or +0.5. (Default value: 0 off 0 . Assigns values to properties.e. and the number of successful steps. 10. (Default value: 1 for all ode solvers except ode45.1) vs. (Default value: 10−6 .. This might be useful in “optimizing” the performance of the ode solver if the command seems to be running excessively slowly. when the Jacobian property is not used.e-6. Jacobian A handle to a function which returns the Jacobian. or. This is only used when the Jacobian is calculated numerically. y1 . yn . Y] = ode45(@duffing a. we define an “event” to be whenever the first component of y passes through −0. we can determine the position of the earth when it is closest to the sun and/or farthest away. y0. i. It is possible to plot different components of y using OutputSel.

duffing n.xe is a vector containing the time of each event.5. isterminal. 1. Yevent. 0]. Yevent is a matrix containing the location of each event. If so. y(1)-0. Yevent. and 0 means that either direction triggers an event. direction] = duffing event(t.2. At the initial time. t and y are known and duffing event is called so that the vector (0) y1 + 0.ye is a matrix containing the location of each event. % do not halt when this occurs direction = [0. (We could let duffing event be a primary function. such as determining the apogee and perigee of the earth’s orbit.5 isterminal = [0.. If the result is stored in the structure sol. 10.) There are a number of steps we have to carry out to turn “events” on. can be calculated.5 i. the new output is sol. If the values have different signs in some row. then direction is checked to determine if the values are passing through zero in the correct direction or if either direction is allowed. index event] = ode45(. we have to use the odeset command. @duffing event).). duffing event is called again and e(1) is calcu- lated and compared elementwise to e(0) . In some cases. indexevent] = ode45(@duffing n. −1 means the value must be decreasing through zero for an event to occur. it does not state what event or events to watch for.. this only tells the ode solver that it has to watch for one or more events. No matter how we describe the event. tevent. such as this example it is easy to put an event into this form. sol. However. the time at which the element is zero is estimated and the ode is solved again to obtain a more accurate estimate. 0 Events 0 . This procedure continues until the zero is found to the desired accuracy. y0. First. Then isterminal is checked to see if the run should be continued or should be stopped. Three vector arguments are output: value – A column vector of values which are checked to determine if they pass through zero during a time step. We have chosen duffing n since we have created the nested function duffing event. Y. we now discuss how an event is actually calculated. Instead. tspan. [t. Any and all events that occur are output by the ode solver through these three additional variables: tevent is a vector containing the time of each event. In other cases.. 0].e-6. and sol. Since the function duffing event might appear confusing. params). y) value = [y(1)+0. isterminal – A column vector determining whether the ode solver should terminate when this par- ticular event occurs: 1 means yes and 0 means no. or duffing p2 and duffing c. The final step is that the left-hand side of the calling statement must be modified to [t. Another interesting ode is van der Pol’s equation y 00 − µ(1 − y 2 )y 0 + y = 0 127 . duffing p. isterminal and direction are returned.ie is a vector containing which value in the vector value passed through zero. Y. % check whether y(1) passes through ±0.e. value. function [value. direction – A column vector determining how the values in value should pass through zero for an event to occur: 1 means the value must be increasing through zero for an event to occur. In addition. Advanced Commands ing the ode45 statement by params = odeset( 0 RelTol 0 . % an event occurs when y(1) passes through % zero in either direction end Note that we can define the right-hand side of Duffing’s equation by using duffing a.5 e(0) = (0) . duffing is called and the solution y(1) is calculated at time t(1) . tevent. as far as the ode solver is concerned an event only occurs when an element of this vector passes through zero. y1 − 0. Next. and index event is a vector containing which value in the vector value passed through zero.5]. we describe what an event is in this new function. the calculation is more complicated. but there is no reason to do so. where we create a new nested function in the primary function duffing ode.

end ˆ for the elements determined by Vdp pattern. since they might be needed for a nastier ode.1. let µ = 1 and solve the ode with initial conditions y(0) = 1 and y 0 (0) = 0 for t ∈ [0. we include them by using Vdp pattern = sparse([1 2 2].1)) subplot(2. Instead. without loss of generality. [2 1 2]. −2µy1 y2 − 1 µ(1 − y12 ) The right-hand side can be coded as a nested function inside a primary function by function vdp ode(mu. 0 JPattern 0 . end ˆ end This is not stiff unless µ is “large”. 10.2.. that the center of our coordinate system is the initial location of the ball. But beware because the ball may never attain this 128 . Let the x axis be the horizontal axis along the direction of flight and z be the vertical axis. Repeat this procedure using µ = 10 and increase the final time. 100] using ode45. However. [1 1 1]. Then let µ = 100. Then. mu*(1-y(1) 2)*y(2)-y(1)]. and the x val- ues and times when the ball reaches the height h > 0. %%%%% nested function follows function deriv = vdp n(t. The initial condi- tions are x(0) = 0 . Note: Plotting the trajectory by plot(t. z(0) = 0. For example.1) plot(t. [0 final time]. 2. until the time required to plot a few oscillations becomes “very large”. opt). tspan. and we want to follow its motion until it hits the ground. y0). Y) is not very instructive. y0. plot the result and note the number of ele- ments in t. We also want to determine four “events” in the ball’s flight: the highest point of the trajectory of the ball and the time it occurs. -2*mu*y(1)*y(2)-1 mu*(1-y(1) 2) ]. params = odeset( 0 Jacobian 0 . use subplot(2. Then use ode15s and note the huge difference in the time required. As a first order system it is 0 y1 y2 = y2 µ(1 − y12 )y2 − y1 and its Jacobian is 0 1 J= . y0. @vdpj n.1. 2).2) plot(t. the distance it travels and the time it hits the ground. Y(:. Y] = <ode solver>(@vdp n. y) % vdpj n: Jacobian for van der Pol’s equation J = [ 0 1.8 meters/second is the acceleration on the ball due to the earth’s gravity. so that you still see a few complete oscillations. By the way. Y(:. final time) ode45(@vdp n. Using Newton’s laws we obtain the ode system x00 = 0 and z 00 = −g where g = 9. y) deriv = [y(2). Vdp pattern): [t.2)) Our final example is slightly more complicated. There is no need to use the ode solver parameters JPattern or Jacobian in this example because this ode is so “nice”. where the Jacobian is calculated numerically using the nested function function J = vdpj n(t. and z 0 (0) = s sin α where we assume. if necessary. Suppose we kick a ball into the air with initial speed s and at an angle of α. Advanced Commands where µ > 0 is the only parameter. etc. 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. x0 (0) = s cos α .

2. y3 = z. (If we would include the effects of air resistance on the ball. our aim is to give an ex- ample of how to use many of the advanced features of MATLAB’s ode solvers.) We convert Newton’s laws to the first-order system 0 y1 y2 y2 0 = y3 y4 y4 −g by letting y1 = x. 10. y2 (0) = s cos α . so we cannot give the final time. In addition. Instead. z vs. we want the relative error to be 10−6 . y3 (0) = 0 . Finally. we want the trajectory (i. then these odes would become nonlinear and would not be solvable analytically. The following is a completely self-contained example using nested functions.. y2 = x0 . 129 . Advanced Commands height! Although these odes can be solved analytically (consult any calculus book). and y4 = z 0 The initial conditions are y1 (0) = 0 . One complication with solving this system numerically is that we do not know when the ball will hit the ground. 10s/g which is much greater than needed and we let the program stop itself when the ball hits the ground.e. we use a time. x ) to be plotted automatically. and y4 (0) = s sin α .

Yevent. Consider the ode P (t)y 00 (t) + Q(t)y 0 (t) + R(t)y(t) = 0 where P (t). y0. y) % gravity event: determines the events value = [y(3). we only provide a very simple example which uses it. direction] = gravity event(t. [1 3]). speed*cos(angle*pi/180).3) Yevent(4.0) with initial % speed and angle (in degrees) given. It is very similar to the func- tions we have already discussed. .3) Yevent(2. 1. end %%%%% nested functions follow function gravity init % gravity init: Initialize everything tspan = [0 10*speed/g]. z’ = 0 isterminal = [1.. 0]. (2) = time ball hits ground % (3. The solution is denoted by 130 . .4) will not be used if height > z value at peak g = 9. y0. index event] = ode45(@gravity. if length(tevent) == 2 times = tevent. % 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. gravity init() [t.. and height do not need to be passed into the nested func- tions. % halt only when z = 0 direction = [-1. params). -g]. Advanced Commands function [times. We consider a linear second-order ode in a neighborhood of a regular singular point.1)]. and params do not need to be passed out.8. values = [Yevent(1. 20. end function [value. params = odeset( 0 RelTol 0 . Y. end function deriv = gravity(t. isterminal.1) Yevent(3. else times = tevent([2 4 1 3]).e-6. y(4). z-height = 0. -1].1) Yevent(1.2. values] = gravity ode(speed. The singular points of this ode are the values of t for which P (t) = 0.4) = x values when ball attains height % Note: (3. values = [Yevent(2.. but there is one important difference.. (2) = x value when ball hits ground % (3. Q(t). tspan. . . 0. 10. tspan.. Similarly.1) where n is a nonnegative integer and the initial condition is given at t = 0. If t0 is a singular point.. A “common” ode of this type is Bessel’s equa- tion t2 y 00 (t) + ty 0 (t) + (t2 − n2 )y(t) = 0 for t ≥ 0 (10. y) % gravity: Calculates the right-hand side of the ode deriv = [y(2). MATLAB also has the function ode15i which solves fully implicit odes. @gravity event. tevent. angle. 0 OutputFcn 0 . y0 = [ 0. 0 Events 0 . angle. y(3)-height. Although it is a very powerful function. height) % gravity ode: The trajectory of a ball thrown from (0. and R(t) are polynomials with no common factors..1)]. speed*sin(angle*pi/180) ]. 0. % z = 0. % times: (1) = time ball at peak. 0 OutputSel 0 . 0 Refine 0 .. 0 odephas2 0 . it is a regular singular point if limt→t0 (t − t0 )Q(t)/P (t) and limt→t0 (t − t0 )2 R(t)/P (t). 0. speed. 0. y(4)].4) = time ball attains height % values: (1) = z value at peak.

y0. yp0) >> plot(t. Boundary-value odes are also odes of the form d y = f(x.t 2 *yp(2)+t*y(2)+(t 2 -1)*y(1)].Y] = ode15i(g. However. If we write Bessel’s equation as n2 00 1 0 y (t) + y (t) + 1 − 2 y(t) = 0 (10.1)) Implicit ODE Solver ode15i Stiff ode solver for the fully implicit ode f(t. y0 ) = 0 so that y10 − y2 g(t.1) is preferred to (10. but we also have to input T y0 (0) = y10 (0). The free initial condition is y 0 (0) and for this example we choose y 0 (0) = 1.0] >> [t. t y2 + ty2 + (t2 − 1)y1 Finally. >> tspan = [0 10] ˆ ˆ >> y0 = [0. y 0 ) = 0. Differentiate (10. Boundary-Value Ordinary Differential Equations Jn (t) and. y. When we convert Bessel’s 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. We can solve Bessel’s equation for t ∈ [0. y) for x ∈ [a. Now set t = 0 to obtain y 00 (0) = 0. 11. y). yp) [yp(1)-y(2). we will concentrate on n = 1.2) for t ≥ 1 with the initial conditions that y(1) and y 0 (1) are given.2).2) t t we clearly have a problem at t = 0 and for t ≈ 0. tspan. y.1] >> yp0 = [1. but this form has a problem when t = 0. Boundary-Value Ordinary Differential Equations In addition to initial-value ordinary differential equations there is a second type of odes that MATLAB can solve numerically. a completely different method of solution is required for t ≥ 0 and the form (10. y. y. 1)T . It is easy to calculate y10 (0) = y2 (0). 10] by >> g = @(t. for specificity. At t = 0 the ode reduces to −y(0) = 0 and so we require y(0) = 0. we not only have to input the initial condition y(0) = (0. b] dx 131 . 11. we write it as g(t. y0 ) = 2 0 .1) with respect to t to obtain t2 y 000 (t) + 3ty 00 (t) + t2 y 0 (t) + 2ty(t) = 0 and differentiate it again to obtain t2 y 0000 (t) + 5ty 000 (t) + (t2 + 3)y 00 (t) + 4ty 0 (t) + 2y(t) = 0 . but y20 (0) ≡ y 00 (0) is more complicated. y20 (0) . Instead. The ode solvers we discussed previously can han- dle (10. Y(:.

In addition. by y(1) − y(0) φ y(0). end where we use global to input which ode to use and . For simplicity.4) y(1) + 2y 0 (1) − 3 Finally. y(1) = =0. 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. -(exp(y(1))+2*y(2))/eps]. Since these boundary conditions are particularly simple. y) global which ode eps if which ode == 1 yp = [y(2).e. If the boundary conditions are sep- arated. These two odes are quite simple. we will only consider two closely related second-order odes. n = 2. We solve the boundary value problem by >> sol = bvp4c(<right-hand side>.5) y 0 (1) − y 0 (0) The primary MATLAB function is bvp4c. yb(1)]. y(1) = =0..4).1b) dx dx for x ∈ [0. The boundary condition is given by function bc = nlode bc(ya. yb) bc = [ya(1). For our example the ode given by function yp = nlode(x. Boundary-Value Ordinary Differential Equations where y ∈ Rn but conditions are given at both ends of the interval. (11. we could use periodic boundary conditions. which are non-separated. However. y(1) = =0. the functions bvpinit and deval are also needed.2) y(1) which are called Dirichlet boundary conditions. -eps*exp(y(1))-2*y(2)]. Consider the two nonlinear boundary-value ordinary differential equations d2 y dy 2 (x) + 2 (x) + ey(x) = 0 (11. 11. (11. we have to choose an initial guess for y(x) using bvpinit by either >> bvpinit(x. (11. but also quite interesting and challenging to solve for certain intervals in . If the boundary conditions are non-separated. yb(1)+2*yb(2)-3]. for mixed boundary conditions (11. 1] where > 0. then k conditions are given at x = a and n − k other conditions are given at x = b. (11.1a) dx dx and d2 y dy 2 (x) + 2 (x) + ey(x) = 0 (11. we also include the function function bc = nlode bc2(ya. To allow any of these boundary conditions we write the boundary conditions as φ y(a).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). else yp = [y(2). This example should enable you to study any boundary-value ode. <initial guess>) There are two functions we need to write: odefun is f(x. i. then the conditions at x = a and at x = b are related. Our boundary conditions are y(0) φ y(0). <boundary conditions>. y) and bcfun is the boundary conditions. y(b) = 0 where φ ∈ Rn . y init) 132 . yb) bc = [ya(1)-ya(2)-1.

@nlode bc. y2]). However. >> y1 = 4*A*x. >> A = 1. 21). @nlode y ic).x). 1. 133 . >> y2 val = ???. Boundary-Value Ordinary Differential Equations or >> bvpinit(x. Warning: This is dangerous because future versions of Matlab might change the fieldnames of the struc- ture solinit.*(1 .2*x). it works for now.:). >> solinit. >> sol = bvp4c(@nlode. >> x = linspace(0.2*x). >> solinit = bvpinit(x. [y1. 1. If you really. >> plot(xpt.y2]. the numerical solution y by %%%%% script m-file: nlode2 >> xpt = linspace(0. 21). >> solinit = bvpinit(x.x). y2 val]). @nlode y ic). specify the structure solinit directly by entering >> x = linspace(0. then do not use bvpinit. % WRONG This fails because y1 and y2 must be scalar variables and not vectors. The solution is contained in sol and is extracted by deval. Thus the initial guess is y1 = y1 val*ones(size(x)) and y2 = y2 val*ones(size(x)). 11. >> solinit. where y1 val and y2 val are scalar values.*(1 . For example.y = [y1. Ypt(2. 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. >> y2 = 4*A*(1 . 1. >> solinit = bvpinit(x. >> y1 = 4*A*x.x = x. >> y1 val = ???. really need y1 and y2 to be vectors. 1. Ypt(1. where nrode y ic is written as function y ic = nlode y ic(x) global A y ic = [4*A*x.x). >> y2 = 4*A*(1 . 21). >> e = 3. 1.*(1 . 101). Instead. We are finally ready to solve this ode by %%%%% script m-file: nlode1 >> global which ode e >> global A >> which ode = 1. solinit). 0 r 0 ) Having done all this work. xpt. This is often unacceptable because constant initial guesses may be so far from the solution that convergence cannot be obtained. >> solinit = bvpinit(x. >> Ypt = deval(sol. xpt). 21). <initial guess function>) For example. What we would like to do is >> x = linspace(0. if xi = (i − 1)∆x where x1 = 0 and xn = 1 then we determine. and plot. 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.:). The only alternative is to write >> x = linspace(0. [y1 val. 4*A*(1-2*x)]. 1. 21).

The second solution rises much more rapidly and then decays much more rapidly so that. It works similarly to odeset which modifies parameters in ode45. When = 0. Also.) This is a good test of any boundary-value solver. 0 r 0 ) %%%%% nested functions follow function y ic = nlode y ic(x) y ic = [4*A*x. e. xpt = linspace(0. else yp = [y(2). (The two solutions merge and disappear. 11. Frequently there are values of the parameter(s) for which “good” initial iterates are known. solinit = bvpinit(x. the ode (11.82 and no solutions for ' 3. the continuation method is very helpful. nr points) % nlode all: boundary-value solver using bvp4c % which ode = 1 y’’ + 2 y’ + e exp(y) = 0. This solution can only be found by trying “large” initial guesses (e. 1. The “interesting” feature of this ode is that for 1 the solution rises rapidly from y(0) = 0 to y(x) ≈ log 2 for x = O() and then decays gradu- ally so that y(1) = 0. If = 0. for the ode (11. y(0) = y(1) = 0 % A = the initial guess is y = 4 A x (1 . choosing A to be large in nlode y ic ). the solution is returned so it can be used in the MATLAB workspace.1b) it is very difficult to determine “good” initial guesses for even the smaller solution when 1 since the solution grows so rapidly.82. nr points).x). this is true for our example — but it is not true for many examples. And this is only the first solution.1b) is much more challenging for 0 < 1. plot(xpt. xpt). yb(1)]. Again. The reason we chose these particular odes is to “check out” bvp4c. For the ode (11. The standard method to use to obtain a “good” initial iterate is the continuation method.1a) there are two solutions for 0 ≤ / 3. -(exp(y(1))+2*y(2))/e].x) % nr points = number of equally spaced points in initial guess x = linspace(0. 4*A*(1-2*x)]. yb) bc = [ya(1).:). y(0) = y(1) = 0 % = 2 e y’’ + 2 y’ + exp(y) = 0 . A. Ypt(1. xpt. etc. @nlode bc. 101). For the ode (11. the function bvpset can be used to create or modify parameters needed by bvp4c. The only difficulty with this method is that there might be more solutions.:).1 the resulting analytical solution is a very good approximation to the numerical solution. end end function bc = nlode bc(ya. It is very challenging for a boundary-value solver to be able to capture this rapid rise. 1. sol = bvp4c(@nlode. @nlode y ic). The numerical solution can then be used as an initial guess for a larger value of . In fact. Incidentally.1a) if 1 we can approximate ey by the Taylor series expansion (1 + y) and solve the resulting linear ode. y) if which ode == 1 yp = [y(2). For example. -e*exp(y(1))-2*y(2)]. etc. solinit).*(1 . Some- times it takes a “good” initial choice to obtain convergence. You can use this solution as the initial guess for = 0. Ypt(2. again..g.2. Sometimes. Ypt = deval(sol. any “halfway decent” initial choice of y will con- verge to a solution. y(1) = 0.1 there is a second solution whose maximum is over 8. For this solution y 0 (0) ≈ 35 which indicates how rapidly the solution is growing at the left endpoint. end end This m-file is easy to read and easy to debug and easy to modify. Start 134 . One final point needs to be emphasized. Boundary-Value Ordinary Differential Equations function sol = nlode all(which ode. a “bad” choice will never converge to the de- sired solution. end function yp = nlode(x.

(Since the two odes are identical when = 1 you can use the solution you found to ode (11.y) and boundary conditions(ya. The polynomial can be evaluated at x by >> y = polyval(q. (1. . Polynomials and Polynomial Functions with a “large” value of .e. deval(x. 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.1a). 1).01 we have y 0 (0) ≈ 130 and when = 0.) A practical example which uses polynomials is to find the “best” fit to data by a polynomial of a partic- ular degree. is represented by the vector q = (c1 . you might well find an ode for which this is not true. 0. a vector. The user supplied functions are f(x. bvpinit(x.8. . 12. <initial guess function>) ing y directly or by using a function y = initial guess function(x). Numerically solves y0 (x) = f(x. and choose a “reasonable” initial guess. If A is a square matrix.001 we have y 0 (0) ≈ 1300.yb) where ya = y(a) and yb = y(b).1b) will converge to the single solution. i. (1. c2 .y) Calculates the initial guess either by giv- o bvpinit(x. x) where x can be a scalar.) Then slowly decrease . However. 12. with given boundary conditions and an initial <initial guess>) guess for y. Boundary-Value Solver bvp4c(<right-hand side>. . these are passed to bvp4c when it is executed. cn )T . then p(A) = c1 An−1 + c2 An−2 + · · · + cn−1 A + cn is calculated by >> polyvalm(q. y) for x ∈ [a. when = 0.2.5). c1 is the coefficient of the highest power of x and cn is the coefficient of the lowest power. −1). say = 1. we want to remind you that for the odes we have discussed here almost any “halfway reasonable” initial choice for the ode (11. −2). Polynomials and Polynomial Functions In MATLAB the polynomial p(x) = c1 xn−1 + c2 xn−2 + · · · + cn−1 x + cn . . A) (See Section 15 for more details on this type of operation. In conclusion.. (0. For example. (−1. bvpset Assigns values to properties. You can easily calculate the roots of a polynomial by >> r = roots(q) Conversely. y) = right hand side(x. 2) and we want .y soln) Interpolate to determine the solution at x.1a) will converge to one of the two solutions and for the ode (11. Suppose the data points are (−3. b] <boundary conditions>. −0. or a matrix.

Defining the data points more abstractly as (xi . yi ) . to find the “best” fit by a straight line.

i = 1. = . n and the desired straight line by y = c1 x + c2 . . . . 2... xn 1 yn 135 . . the matrix equation for the straight line is x1 1 y1 x2 1 c1 y2 . c2 . .. . . .

enter >> V = vander(x) >> V(: .. There are a number of commands to interpolate data points . y = c1 xm + c2 xm−1 + · · · + cm+1 . >> yy = polyval(c.. generates the square Vandermonde matrix with m = n − 1.e. To generate the n×(m − 1) Vandermonde matrix we want. Instead. . Given a set of data points (xi . the number of coefficients in the polyno- mial). You can also integrate a polynomial by >> q int = polyint(q) in which case the constant term is 0. we find the least-squares solution c = (c1 . You can also find a local maximum or minimum of the polynomial p(x) by finding the zeroes of p0 (x). For example.. xm n xm−1 n ··· xn 1 cn The matrix V is called a Vandermonde matrix .2. .. 100).. c) for some constant c in which case the constant term is c. Warning: The Vandermonde matrix is approximately as badly conditioned as the Hilbert matrix which was discussed in Section 5. or by >> q int = polyint(q. .. This entire procedure can be carried out much more easily by entering >> q = polyfit(x. i. . The coefficients of p0 (x) are calculated by >> q deriv = polyder(q) where q is the vector of the coefficients of p(x). . there is no solution to this overdetermined linear system. and c = .. . m-1) where the third argument is the order of the polynomial (i. . 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. 1:m-1) = [].. Polynomials and Polynomial Functions In general. >> plot(xx. 1)] \ y We can plot the data points along with this straight line by >> xx = linspace(min(x).e. The statement >> V = vander(x). yy. y. y. c2 )T by >> c = [x ones(n. max(x). xx). 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). cond(vander([1 : 10])) = 2×1012 whereas cond(hilb(10)) = 2×1013 . . x. by calculating the least-squares solution to Vc = y where xm 1 x1m−1 ··· x1 1 c1 xm 2 xm−1 2 ··· x2 1 c2 V= . 0 o 0 ) We can find the “best” fit by a polynomial of degree m < n. 12.

in any number of dimensions. The simplest command in one dimension to interpolate the points (xi . yi ) .

yvalues is the vector of the interpolated values.e. (This is the default.. That is. One additional require- ment for this command is that the elements of x are monotonic. i. 0 linear 0 : Linear splines are used to connect the given data points. to make it easy for the function to determine which data points are “near” the desired value. 1 ≤ i ≤ n is >> yvalues = interp1(x. straight lines connect each pair of adjacent data points. The additional constraints needed to obtain unique polynomials are that the the two polynomials which overlap at each interior data 136 . either all in increasing order or in decreasing order. 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. That is. xvalues. and <method> is an optional argument specifying the method to be used. <method>) where xvalues is a vector of the values to be interpolated. cubic polynomials connect each pair of adjacent data points. y.) 0 spline 0 : Cubic splines are used to connect the given data points.

Polynomial Functions interp1(x. Interpolation really means interpolation. In par- ticular. this interpolation is better at preserving the shape of the data. polyfit(x. Instead. If a value lies outside the interval [x1 . polyder(q) Calculates the derivative of a polynomial given the vector of the coefficients of the polynomial. 137 . y) >> yvalues = ppval(pp. polyvalm(q. An optional second argument is used to obtain a different constant value. y. yi ) . ppval evaluates the piecewise polynomial calculated by pchip or spline. NaN is returned. poly(<roots>) Calculates the coefficients of a polynomials given its roots. The second command interpolates the piecewise polynomial at the x values given by the vector xvalues. This is similar to spline but the second derivatives need not be continuous at the interior data points. y. <method>) Interpolates any number of values using the given data points and the given method. A) Evaluates the polynomial p(A) where A is a square matrix. on intervals where the data is monotonic so is the piecewise polynomial. Similarly. this value is returned whenever the value lies outside the interval. • If the fifth argument is 0 extrap 0 . x) Evaluates the polynomial p(x). xn ] then. y) >> yvalues = ppval(pp. An alternate way to interpolate these points is by using the two commands >> pp = spline(x. xvalues) to generate and interpolate the cubic spline or >> pp = pchip(x. xvalues) to generate and interpolate the piecewise cubic Hermite polynomials. Polynomials and Polynomial Functions point have the same first and second derivatives at this point. This can be changed by adding a fifth argument: • If the fifth argument is a number. extrapolation (using the same method) is used. vander Generates the Vandermonde matrix. 0 pchip 0 : Piecewise cubic Hermite polynomials connect each pair of adjacent data points. With it you can specify precisely the boundary conditions to use. interp2 Interpolates in two dimensions.) polyint(q) Calculates the integral of a polynomial given the vector of the coefficients of the polynomial with the constant value being 0. the command pchip can be used instead of using interp1 with the method pchip or cubic. pchip Cubic Hermite interpolation. 12.1 it calculates the unique polynomial of lowest degree which passes through all the data points. by default. 0 cubic 0 : The same as pchip. n) Calculates the coefficients of the least-squares polynomial of degree n which fits the data (xi . and on intervals where the data is concave up or down so is the piecewise polynomial. The first command generates the structure pp which contains all the information required to obtain a unique piecewise polynomial. interp3 Interpolates in three dimensions. interpn Interpolates in n dimensions. xvalues. roots(q) Numerically calculates all the zeroes of a polynomial given the vector of the coefficients of the polynomial. spline Cubic spline interpolation. polyval(q. (If n = length(x) . The command spline can be used instead of using interp1 with the method spline.

the function will have parameters that need to be set. Alternately. Then we can use closure. %%%%% nested function follows function y = fcos n(x) y = a*cos(x) + b*x. as we discussed previously. . <options>) where xstart is either x0 or [xmin xmax]. as already discussed in Section 10. .. xmax) where the signs of the function must differ at the endpoints of the interval. b. The full argument list is >> fzero(<function handle>. so that the parameters can be set outside of fzero. end end It sometimes happens that the function has already been coded in a separate file. xmax) 138 . x0) >> fzero(<function handle>. >> b = ???. Frequently. >> fcos c = @(x) fcos p(x.e. x0) x0 is a guess as to the location of the zero. >> fcos a = @(x) cos(a*x) + b*x. for example. The parameters a and b are determined when the function fcos c is generated and so are passed indi- rectly into fzero MATLAB can also find a local minimum of a function of a single variable in an interval by >> fminbnd(<function handle>. >> yzero = fzero(fcos a. >> b = ???. >> opt = optimset( 0 <Prop 1> 0 . Numerical Operations on Functions MATLAB can also find a zero of a function by >> fzero(<function handle>. xstart). Numerical Operations on Functions 13. >> fzero(<function handle>. 0 <Prop 2> 0 .) changes the options included in the argument list and >> fzero(<function handle>. xmin. We can “tune” the zero find- ing algorithm by using the function optimset to create a structure which changes some of the default parameters for fzero. xstart. a. 13. Enter >> help optimset for a discussion of how optimset works and >> optimset(@fzero) to see the default parameters. xstart. For example.. . it is a primary function m-file. >> yzero = fzero(fcos p. fzero cannot find the zero of the function f (x) = x2 . such as function y = fcos p(x. b). xstart). b) % fcos: f(x) = cos(a*x) + b*x y = a*cos(x) + b*x. a. or by using a nested function function x zero = fzero example(a.. i. ) executes fzero with the new options. <Value 2>. xstart) x zero = fzero(@fcos n. This is easily done by entering >> a = ???. [xmin xmax]) finds a zero in the interval x ∈ (xmin. That is. <arg 2>. we can find a zero of the function f (x) = cos ax + bx by using an anonymous function >> a = ???. . Note: The function must cross the x-axis so that. xstart). <arg 1>. <Value 1>.1. opt.

we have not found a zero of f.00029751371046)T ). 1. b.1324 . The answer might not seem to be very accurate. the termination tolerance on the function value. options) MATLAB can also find a local minimum of a function of several variables by >> fminsearch(<function handle>. a = −∞ or b = +∞ ) or fully infinute ( a = −∞ and b = +∞ ).. 0 TolFun 0 . iterate0) where iterate0 is a vector specifying where to begin searching for a local minimum. −2. However. the value of the function at this point is 1. [0 0]. quadl uses the more accurate formula and so should require many fewer function evaluations. trace) where tol sets the relative tolerance for the convergence test and information about each iterate is printed if trace is non-zero. which is a variant of Gauss quadrature. b) The full argument list is >> quad(<function handle>. The second is quadl which uses adaptive Gauss-Lobatto quadrature.0627 ./(1 + x.99999998869692. is the same. 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 first is quad which uses Rb adaptive Simpson’s method. This command is more general than the previous two because it is much more general: • The interval can be half-infinite (i. For example.).0000 − 2. >> fminsearch(fnctn. In other words.e. . For example. suppose we want to find a zero of the function x1 + x2 + sin(x1 − x2 ) f(x) = . For example.8818×10−16 (the actual value is 2π ) and the error in 139 . the error in >> f = @(x) 1. x1 − x2 + 2 cos(x1 + x2 ) Instead. We are not done since we still have to calculate g(xmin ). 1.e-8. we have found a zero of f — if it is not zero. . For ex- ample. . the full argument list is >> fminbnd(<function handle>. 1.00010410231166)T . . if we enter >> fnctn = @(x) (x(1) . To determine the accuracy MATLAB is using to determine the minimum value type >> optimset(@fminsearch) The value of TolX. For example.1) 2 + (x(2) + 2) 4. Since the value of funct at this point is 2. 1)T .e-8) >> xmin = fminsearch(f. If the minimum value is 0.00000004979773. If our initial condition is (1. the location of a zero and/or a local minimum of a function might not be as accurate as you might expect.03×10−14 . the termination tolerance on x. • In addition the integrand can have an integrable singularity. a. 2). To evaluate a f (x) dx by Simpson’s method enter >> quad(<function handle>. if f is defined an an anony- mous function the result of >> xmin = fminsearch(f.0003)T (actually (1. >> quadgk(f.45×10−16 . However. Numerical Operations on Functions As with fzero. Be careful. [0 0] 0 ) ˆ ˆ we obtain (1. which is quite small. There is no direct way to find zeroes of functions of more than one dimension. inf) ˆ is 8. The third is quadgk which uses adaptive Gauss-Kronrod quadrature. MATLAB can also calculate definite integrals using three commands. it can be done by using fminsearch.4×10−9 which is small — but is it small enough? We can decrease the termination tolerance by >> opt = optimset( 0 TolX 0 . xmax. tol. 13. −2. a. we can find a minimum of g(x) = f12 (x) + f22 (x). This is ≈ 2.3×10−17 we can assume that we have found a zero of f. [0 0]) is xmin = (−. is 10−4 and the value of TolFun. the answer is about as accurate as can be expected. opt) Since g(xmin ) = 2. xmin. the result is (0. 0. .

y. MATLAB can also calculate the double integral Z xmax Z ymax f (x. fzero(<function handle>. y) dxdy xmin ymin by >> dblquad(<function handle>.. zmin. b. x0) Numerically calculates a zero of a function given the initial iterate. Discrete Fourier Transform There are a number of ways to define the discrete Fourier transform. x0 can be replaced by a 2- vector of the endpoints of the interval in which a zero lies. z) dxdy dz xmin ymin zmin by >> triplequad(<function handle>. iterate0) Numerically calculates a local minimum of a multi- dimensional function given the the initial iterate vector. <Value 1>.) Allows you to modify the parameters used by fzero. ymin. d) Numerically evaluates a double integral. zmax) Numerical Operations on Functions dblquad(<function handle>. fminbnd. quadl(<function handle>. fminbnd(<function handle>. In this section we show exactly how to discretize the contin- uous Fourier series and how to transform the results of MATLAB’s discrete Fourier transform back to the continuous case. we choose to define it as the dis- cretization of the continuous Fourier series. Discrete Fourier Transform >> g = @(x) exp(sqrt(x))/sqrt(x). xmax. c. xmin. 14. 1) is −2. 14.3670×10−13 (the actual value is 2(e − 1) ). We are presenting the material in such detail because there are a few slightly differ- ent definitions of the discrete Fourier transform. xmin. a. >> quadgk(g.1) T T k=1 140 . xmin. a. a. ymax. and fminsearch. we present the definition which follows directly from the real Fourier series. T ] (14. . 0. quadgk(<function handle>. ymin. xmax. b) Numerically evaluates an integral using the adap- tive Gauss-Kronrod method. optimset 0 <Prop 1> 0 . ymax) It can also calculate the triple integral Z xmax Z ymax Z zmax f (x. b) Numerically evaluates an integral using the adap- tive Gauss-Lobatto method. a. xmax) Numerically calculates a local minimum of a one- dimensional function given the endpoints of the interval in which to search fminsearch(<function handle>. quad(<function handle>. b) Numerically evaluates an integral using Simpson’s method. xdi A “reasonable” continuous function f which is periodic with period T can be represented by the real trigonometric series ∞ X 2πkt 2πkt f (t) = a0 + ak cos + bk sin for all t ∈ [0. The interval can be infinite and/or the function can have an integrable singularity..

b2 . The power of the function f (t) is† Z T. a1 . and ak and bk are the coefficients of the k th mode. 2 bk = f (t) sin kt dt T 0 The coefficients a0 . a2 . . ∞) . . . 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. . are called the real Fourier coefficients of f . . . and b1 .

1 .

f (t).

2 dt .

i.2) k=−∞ where † 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. where I is the current and t is the time it takes for the charge to move between the two terminals. However.. P = T 0 so that ∞ 1X P = |a0 |2 + |ak |2 + |bk |2 .. The work done on the charge is W = qV = ItV . T ] (14. we will stick to the common usage. t R Thus. if we consider f (t) to be the voltage or the current of some signal. the power spectrum. Consider a particle which is under the influence of the constant force F~ . where ~r is the vector from P0 to P1 .e. Since eiαt + e−iαt eiαt − e−iαt cos αt = and sin αt = . If the particle moves from the point P0 to P1 then the ~ q work done to the particle is F ~r . i. the instantaneous power in the signal is proportional to f 2 (t) and the average power is proportional to 1 T . V = IR and the power is W V2 = IV = I 2 R = P = . If R is the resistance in the circuit. The power of the particle is the work ~ q~v where ~v = ~r/t. consider a charge q which is moving between two terminals having a potential difference of V . is |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. To understand the physical significance of power. we begin with the definition of work. 2 2i we can rewrite the real Fourier series as the complex Fourier series ∞ X 1 − ibk )e2πikt/T + 12 (ak + ibk )e−2πikt/T f (t) = a0 + 2 (ak k=1 so that ∞ X f (t) = ck e2πikt/T for all t ∈ [0. done per unit time.e. 2 k=1 The power in each mode. F Next.

.

Z .

2 f (t).

T 0 141 . dt .

N − 1 k=−M or.4). . . (14. 1. . 2. The γ’s are the coefficients in the discrete complex Fourier series. γM is that the c’s are the coefficients in the continuous complex Fourier series. N − 1 (14.† That is. . −2. † 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. c−1 . eq.2). M . . . cM by γ−M . The power of f (t) is ∞ X P = |c0 |2 + |ck |2 + |c−k |2 k=1 and the power in each mode is |c0 |2 if k = 0 Pk = 2 2 |ck | + |c−k | if k > 0 . γ−M +1 . . N − 1 (so that 0 = t0 < t1 < · · · < tN −1 < tN = T ). −1. k=−M There are now N = 2M + 1 unknowns (which is an odd number because of the k = 0 mode). . −M + 1. . (Note that these Fourier coefficients are generally complex. We require N equations to solve for these N unknown coefficients. are called the complex Fourier coefficients of f . . 2. We obtain these equations by requiring that the two sides of this ap- proximation be equal at the N equally spaced abscissas tj = jT /N for j = 0. . Discrete Fourier Transform c0 = a 0 ) ck = 12 (ak − ibk ) (14. 142 . . c−M +1 . γM −1 . . and are calcu- lated by (14. .5) N j=0 The reason we have replaced the coefficients c−M . . written as a first-order system. 1.4) k=−M where fj ≡ f (tj ). 1.3). . c−k = 21 (ak + ibk ) The coefficients . We can only calculate a finite number of Fourier coefficients numerically and so we truncate the infinite series at the M th mode. and ck and c−k are the coefficients of the k th mode. cM −1 . . . This linear system can be solved to obtain N −1 1 X γk = fj e−2πijk/N for k = −M. c0 . . (14. . We should choose M large enough that M X f (t) ≈ ck e2πikt/T for all t ∈ [0. 1. 14. . . T ] . . . . c2 .3) for k > 0 . c1 . then c−k = c∗k (by replacing k by −k in the above equation). M X fj = γk e2πijk/N for j = 0. .) We can also calculate ck directly from f by Z T 1 ck = f (t)e−2πikt/T dt for k = .5). eq. M X f (tj ) = γk e2πiktj /T for j = 0. . (14. 2. . . c−2 . 0. and are calculated by (14. . . . 2. . T 0 Note that if f is real. . . .

(i) cs = (0. 0. γ−M +1 . 4. 0. 0. 0. f1 . . 0. γ0 . −4. 0. whereas the nonzero Fourier coefficients of f (x) = sin x = (eix − e−ix )/(2i) are a1 = 1 and c−1 = i/2 but c1 = −i/2. and is generally not equal to the continuous Fourier coefficient ck . T ] . 0. >> x = linspace(0. . but only the fft returns the correct coefficients for sin x. . 0. γM −1 . 0. 4. −0. 0. >> d s = fftshift(c s). .5i). 0. 4. 0. −4. 0. .5. notice that fftshift correctly shifts the coefficients. 0. γ−2 . 0. . returns the vectors cc = (0. fN −1 )T . 0.2) from it.5i. ds = (0. 0.5. 0. 4. . the command fft is correct. 0.5. 0. γM . 0. . 0). k=−M It is our responsibility (using our experience) to choose M large enough that f (t) ≈ fFS (t). 0.5). 4. 0. γM . 0.e. it takes practice and experimentation to determine what “much less than” means. 0. γM −1 . Also. The nonzero Fourier coefficients of f (x) = cos x = (eix + e−ix )/2 are a1 = 1 and c−1 = c1 = 1/2. 0). 0. (i) dc = (0. >> ci c = ifft(cos(x)). 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 . 2*pi. However. . 0. as M → ∞ we have γk (M ) → ck . . Notice that fft and ifft both return the correct coefficients for cos x (up to the scaling of n ). . . and (i) ds = (0. >> di s = ifftshift(c s). 0. 0. 0. n+1). The code >> n = 9. 0. Thus.5.1) and derived the complex trigonometric series (14. 0.5. ifftshift is the inverse of fftshift so ifftshift(fftshift(c s)) = c s. . For a fixed M we generally only have γk (M ) ≈ ck as long as |k| is “much less than” M . −0. γk (M ). >> x(n+1) = []. 14. Discrete Fourier Transform Note: To repeat: the discrete Fourier coefficient γk is a function of M .. . 0. The original function. 0. 0. is recovered by >> 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. 0. γ−1 . Of course.5i. 0). . . 0). 0. . γ1 . 0. γ−2 . cs = (0. 0. 0. f2 . γ−M . 0. . 0. . 0. f2 . We began with the real trigonometric series (14. γ1 . i. . (i) cc = (0. We define the discrete Fourier series by M X fFS (t) = γk e2πikt/T for all t ∈ [0. . >> d c = fftshift(c c).5. .5i). f1 . . The command fftshift changes the order to T γ−M . represented by the vector f. fN −1 143 . . 4.5i. γ−1 . 0. >> c s = fft(sin(x)). >> ci s = ifft(sin(x)). dc = (0.5i. >> di c = ifftshift(c c). That is. 0.5i. >> c c = fft(cos(x)). 0. 0.5). 0. but it multiplies the coefficients by N . γ−M +1 . whereas ifftshift does not — but ifftshift correctly shifts the coefficients back. 0. Warning: One of the most common mistakes in using fft is forgetting that the input is in the order f0 . Given f = (f0 .5i. 0.

0e−08 −7 10 0 200 400 600 800 1000 1200 1400 1600 1800 2000 n For N to be even. cputime to calculate fft(f. γ−2 . which is the method used to calculate the discrete Fourier coefficients by fft and also to recover the original function by ifft. . . . . for short). . . Discrete Fourier Transform while the output is in the order γ0 . it is clear that there is a huge difference in the time required as we vary N . The discrete complex Fourier series is M X −1 fFS (t) = γk e2πikt/T for all t ∈ [0. The figure below shows the cputime needed to calculate fft(f) as a function of N . . γM −1 . γ1 . the vector f has N = 2M + 1 elements. γ1 . γM . . . and the one we drop is γM . . γ−1 γ0 . Since the verti- cal axis is logarithmic. There is only one difficulty with our presentation. and is particularly fast if it a power of 2. γM −1 . .7e−09. . . 2. T ] k=−M 144 . which is an odd number. Now N = 2M is even. γM . As we have already stated. we have to drop one coefficient. . γ−M . . γ−M +1 .n) −3 10 −4 10 cpu time (seconds) −5 10 −6 10 dashed lines are c*n*log2n.The dashed lines show the minimum and maximum asymptotic times as cn log2 n. 14. γ−M +1 . generally works faster if the number of elements of f is even. The Fast Fourier Transform (FFT. c = 2. . γ−1 . not γ−M . γ−2 .

14. Discrete Fourier Transform

and the discrete Fourier coefficients are calculated by

N −1

1 X

γk = fj e−2πijk/N for k = −M, −M + 1, . . . , M − 2, M − 1 .

N j=0

**As before, given f = (f0 , f1 , f2 , . . . , fN −1 )T , the Fourier coefficients are calculated by
**

>> fc = fft(f)/N

The coefficients of the discrete Fourier transform are now contained in fc as

T

fc = γ0 , γ1 , . . . , γM −2 , γM −1 , γ−M , γ−M +1 , . . . , γ−2 , γ−1 .

**The original function, represented by the vector f, is again recovered by
**

>> f = N*ifft(fc)

Note: Since there are now an even number of Fourier coefficients, we can reorder them by using

fftshift, which switches the first half and the last half of the elements. The result is

T

fftshift(fc) = γ−M , γ−M +1 , . . . , γ−2 , γ−1 , γ0 , γ1 , . . . , γM −2 , γM −1 , .

**Also, ifftshift is the same as fftshift if N is even.
**

Warning: Remember that if you reorder the elements of fc by

>> fc shift = fftshift(fc)

you will have to “unorder” the elements by applying

>> fc = fftshift(fc shift)

again before you use ifft.

Note: When N is even we cannot recover γM and so we only know one of the two coefficients of the M th

mode. Thus, we cannot determine the M th mode correctly. Although we cannot give a simple ex-

ample, it occasionally happens that this causes difficulties. The solution is to set γ−M = 0 so that

the M th mode is dropped completely.

We show a simple example of the use of Fourier coefficients from The Student Edition of MATLAB:

User’s Guide. We begin with

%%%%% script m-file: fft ex1

time = 0.6;

N = 600;

t = linspace(0, time, N);

y0 = sin(2*pi*50*t) + sin(2*pi*120*t); % unperturbed signal

ypert = y0 + 2*randn(size(t)); % perturbed signal

figure(1)

plot(t, y0, 0 r 0 ), axis([0 time -8 8])

hold on

pause(1)

plot(t, ypert, 0 g 0 )

(which is contained in the accompanying zip file). This is a signal at 50 and 120 hertz (cycles per unit

time), y0, which is perturbed by adding Gaussian noise, ypert. We plot the periodic unperturbed sig-

nal, and then the perturbed signal, vs. time. Clearly, once the random noise has been added, the original

signal has been completely lost — or has it.

We now look at the Fourier spectrum of y0 by plotting the power at each frequency in

145

14. Discrete Fourier Transform

**%%%%% script m-file: fft ex2
**

fc0 = fft(y0)/N; % Fourier spectrum of unperturbed signal

figure(2)

fc0(N/2 +1) = []; % delete k = N/2 +1 mode

power0(1) = abs(fc0(1)). 2;

ˆ

power0(2:N/2) = abs(fc0(2:N/2)). 2 + abs(fc0(N-1:-1:N/2 +1)). 2;

freq = [1:N] 0 /time;

ˆ

% the frequency of each mode

ˆ

plot(freq(1:N/2), power0, 0 r 0 ), axis([0 freq(N/2) 0 .5])

fcpert = fft(ypert)/N; % Fourier spectrum of perturbed signal

hold on

powerpert(1) = abs(fcpert(1)). 2;

ˆ

powerpert(2:N/2) = abs(fcpert(2:N/2)). 2 + abs(fcpert(N-1:-1:N/2 +1)). 2;

pause(1)

ˆ ˆ

plot(freq(1:N/2), powerpert, 0 g 0 )

(which is contained in the accompanying zip file). First, we plot the unperturbed power, power0, and

then the perturbed power, powerpert, vs. the frequency at each mode, freq. The two spikes in the plot

of the unperturbed power are precisely at 50 and 120 hertz, the signature of the two sine functions in y0.

(For simplicity in the discussion, we have deleted the power in the M th mode by fc(N/2 +1) = [] so

that power0(k) is the power in the (k−1)st mode.) Clearly, the original spikes are still dominant, but the

random noise has excited every mode.

To see how much power is in the unperturbed signal and then the perturbed signal, enter

>> 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 0’s

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 2πkt

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 2πkt

fdst (t) = bk sin

T

k=1

146

15. Mathematical Functions Applied to Matrices

**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 .

. 2. . f (ti ) . . i = 1. . n and the n data points ti .

2. . . . . it generates an error message.n−1 0 ann 0 apnn Thus. 15. 1! 2! 3! (Thus. Recall that the solution of dy (t) = ay(t) for t ≥ 0 with y(0) = yic dt 147 . ifftshift(cf) Unswitches the first half and the second half of the elements of fc. (fftshift and ifftshift are the same if the number of elements is even.) If A is a square diagonal matrix eA is particularly simple to calculate since p p a11 a11 a22 . T Defining the vectors b = (b1 .n−1 an−1. . . n . . 0 e = . b2 . the MATLAB functions dst and idst switch between them by >> f = dst(b) >> b = idst(f) Discrete Fourier Transform fft(f) The discrete Fourier transform of f. (Otherwise. f (tn ) . . p an−1. bn )T and f = f (t1 ). ifft(fc) The inverse discrete Fourier transform of the Fourier coefficients fc. . That is. dst(b) The discrete sine transform of f if it is an odd function where b are the coeffi- cients and f is the function. . idst(f) The inverse discrete sine transform so b = idst(f). fftshift(fc) Switches the first half and the second half of the elements of fc. i = 1. if A ∈ Cm×n where m 6= n then eA does not exist because Ak does not exist if A is not a square matrix.7.n−1 0 eann The MATLAB command >> expm(A) calculates eA if A is a square matrix. . mathematical functions can generally only be applied to square matrices. if A ∈ Cn×n then eA is defined from the Taylor series expansion of ea . . since a a2 a3 ea = 1 + + + + ··· 1! 2! 3! we define eA to be A A2 A3 eA = 1 + + + + ··· . . ean−1. . ea11 A ea22 .) A simple example where eA occurs is in the solution of first-order ode systems with constant coeffi- cients. That is. 0 p a22 . Mathematical Functions Applied to Matrices As we briefly mentioned in Section 2. . f = dst(b). . 0 Ap = . For example. = . f (t2 ).

you only need enter >> expm(A*t) * yic Note: The above statement gives the exact solution to the ode system at t = 10 by >> expm(A*10) * yic You could also use numerical methods.. How- ever. <function handle>) evaluates <function name>(A) for the MATLAB functions exp.. . . Mathematical Functions Applied to Matrices is y(t) = yic eat . 10] in order to obtain a numerical approximation at the final time. yn (t) an1 an2 ··· ann yn (t) i. . log B is calculated in MATLAB by entering >> logm(A) These are the only explicit MATLAB commands for applying mathematical functions to matrices.e.. <function handle>) Calculates <function name>(A) where A must be a square matrix. . sinh. the solution of ··· y (t) y (t) 1 a11 a12 a1n 1 d y2 (t) a21 a22 ··· a2n y2 (t) . = . as discussed in Section 10. there is a general matrix function for the other mathematical functions. B is calculated in MATLAB by entering >> sqrtm(A) Finally. logm(A) Calculates log A where A must be a square matrix. funm(A. . cos. However. To calculate y(t) for any time t. This √ would be much more costly than simply using the analytical solution. . . Similarly. to solve it.. Matrix Functions expm(A) Calculates eA where A must be a square matrix. y0 (t) = Ay(t). . The command >> funm(A. for t ≥ 0 with y(0) = yic dt . and cosh as well as user-defined functions. you would have to solve the ode for all t ∈ [0. Similarly. is y(t) = eAt yic . √ sqrtm(A) Calculates A where A must be a square matrix.. 148 .. 15.. . sin.

31) . The number (or num- bers) shown give the page number of the table where this entry is discussed. 7) \ The solution to Ax = b for A ∈ Cm×n : when m = n and A is nonsingular this is the solution Gaussian elimination./B. 7. separates the arguments in a function. 31) \ Scalar left division. one line at a time.(p.(p. 31) / Scalar division. also.(p.(p. 15) % Begins a comment.(p.. B. 31) ˆ. when m < n this is a solution of the underdetermined system.(p.. b\a = a/b. 7.(p. ends each row when enter- ing a matrix. can separate the elements of each row when entering a matrix. 28) .(p. 31) .. 31) ./ Elementwise division of matrices.(p. 31) Scalar or matrix exponentiation. Elementwise exponentiation of matrices. 31) ˆ Special Characters : Creates a vector by a:b or a:c:b. Continues a MATLAB command on the next line.* Elementwise multiplication of matrices. when m > n this is the least-squares ap- proximation of the overdetermined system. Arithmetical Operators + Addition. 15) ↑ The up-arrow key moves backward in the MATLAB workspace.e..(p. also. 31) * Scalar or matrix multiplication. 9) . 31.(p. i.e.\A = A. Appendix: Reference Tables These tables summarize the functions and operations described in this tutorial.(p.(p. (p. Subtraction. 9) .\ Elementwise left division of matrices i. 7. 7. also. subscripts matrices.(p.(p. Ends a statement without printing out the result. (p. 7) 149 . Ends a statement when more than one appear on a line and the result is to be printed out. 83) . 7.

9) Format Options format short The default setting. 17) load Loads back all of the variables which have been saved previously. (p. 11) format long Results are printed to approximately the maximum number of digits of accuracy in MATLAB. 17) profile Profile the execution time of a MATLAB code. 17) C Abort the statement which is currently executing (i.(p.(p. (p. 9) pi π.(p. 17) type Displays the actual MATLAB code.e. This is very useful for improv- ing the performance of a code by determining where most of the CPU time is spent. 9) i √ −1 . 17) who Lists all the current variables. 9) realmin The smallest “usable” positive real number on the computer. 11) 150 . 17.(p. 17) helpbrowser Loads the main page of the on-line reference manual.(p. 9) NaN Not-a-Number √ (as in 0/0 ). 11) format long g Results are printed in the best of either format long or format long e. 9) eps Approximately the smallest positive real number on the computer such that 1 + eps 6= 1. (p.(p.(p. 15. 9) j −1 . 9) Inf ∞ (as in 1/0 ). Appendix: Reference Tables Getting Help demo Runs demonstrations of many of the capabilities of MATLAB. 17) whos Lists all the current variables in more detail than who.. 11) format long e Results are printed in scientific notation to approximately the maximum number of digits of accuracy in MATLAB. 11) format short g Results are printed in the best of either format short or format short e.(p.(p. (p.(p. 17) lookfor Searches all MATLAB commands for a keyword.(p. 117) save Saves all of your variables.(p. hold down the control key ˆ and type “c”). (p. 66) doc On-line reference manual.(p.(p. 9) realmax The largest “usable” positive real number on the computer.(p.(p.(p.(p. 17) help On-line help.(p.(p. 11) format short e Results are printed in scientific notation. (p. (p. 17) Predefined Variables ans The default variable name when one has not been specified.

(p.(p. 13) rem The remainder after division.(p. 13) where atan2(y. integer. 13) tan Tangent.(p. 13) imag The imaginary part of a complex asecd Inverse secant (result in de.(p. (p.(p. 13) expm1(x) ex − 1. 13) tand Tangent (argument in de- cot Cotangent. 13) acosh Inverse hyperbolic cosine. 13) sqrt Square root. 13) real The real part of a complex num- atand Inverse tangent (result in de. i. 13) csc Cosecant. 13. 13) cos Cosine. 13) atan Inverse tangent. 13) acosd Inverse cosine (result in de.(p. 13) to the point (x. 13) tanh Hyperbolic tangent. 13) conj Complex conjugation. number. 13) grees). csch Hyperbolic cosecant. 13) cosd Cosine (argument in degrees). (p. 13) grees). (p.(p.(p. 13) mod The modulus after division. 13) acoth Inverse hyperbolic cosine.(p. +π] ) from the positive x axis secd Secant (argument in degrees).(p.(p. 13) factorial Factorial function.(p. to the asech Inverse hyperbolic secant. sin Sine.(p.(p.e. 13) atan2 Inverse tangent using two arguments round Round to the closest integer.(p.(p. 13) log10 The common logarithm. 13) 151 . 14) heaviside The Heaviside step function.(p. 13) cosh Hyperbolic cosine.. 13) acotd Inverse cotangent (result in de.e. 13) ber.(p. 13) acsch Inverse hyperbolic cosecant.(p. 13) atanh Inverse hyperbolic tangent. 13) integer.(p. 13) asinh Inverse hyperbolic sine. 13) ceil Round upward to the nearest inte.(p. 13) exp Exponential function.(p.(p..(p. 13) grees). y). 13) sind Sine (argument in degrees).(p. coth Hyperbolic cotangent.(p. 13) acscd Inverse cosecant (result in de. ber. 14) grees). 13) grees). to the asind Inverse sine (result in de.(p. Appendix: Reference Tables Some Common Mathematical Functions abs Absolute value(p. 13) grees).(p.(p.(p. 13) sech Hyperbolic secant. 13) floor Round downward to the nearest angle Phase angle of a complex num. 13) base e.(p. 14) sinh Hyperbolic sine. 13) cscd Cosecant (argument in de- acot Inverse cotangent. 13) sign The sign of the real number.(p.(p. 13) ger.(p. (p. fix Round toward zero to the nearest grees). 13) grees). base 10. 13) (−π.(p. 14) cotd Cotangent (argument in de- acos Inverse cosine. 13) asec Inverse secant. (p. 13) log The natural logarithm.(p.(p.(p. i.(p.(p. 13) acsc Inverse cosecant.(p.(p. 13) asin Inverse sine. 14) grees).(p.(p.(p.(p.(p.(p.x) is the angle (in sec Secant.(p.(p. 13) log1p(x) log(x + 1).

(p.*B Elementwise multiplication. 85) input Displays the prompt on the screen and waits for you to enter whatever is de- sired.(p. 7) fopen Opens the file with the permission string determining how the file is to be ac- cessed. 57) diary Saves your input to MATLAB and most of the output from MATLAB to disk. 85) fscanf Behaves very similarly to the C command in reading data from a file using any desired format. one row per line of input. 57) Arithmetical Matrix Operations A+B Matrix addition. 31) A. i.e. (p. 31) ˆ p. A A n Matrix exponentiation. 31) A-B Matrix subtraction./B. 31) elimination when A is a square non.(p. 83) exactly the same as A.(p. p Elementwise exponentiation. 31) 152 . B. one row per line of input.(p. (p.(p.\A Elementwise left division. 7. 57) csvwrite Writes out the elements of a matrix to the named file using the same format as csvread. B.(p. 85) fprintf Behaves very similarly to the C command in writing data to a file using any de- sired format. 31) ˆ A.(p. print Prints a plot or saves it in a file using various printer specific formats. 31.(p.(p.(p. 57) named file. 7.(p. B ˆ A\b The solution to Ax = b by Gaussian ˆ A.(p. one row per line of input. 7. 10) load Reads data into MATLAB from the named file. It can also be used to display data on the screen. 31) A*B Matrix multiplication./B Elementwise division.. 85) fclose Closes the file.(p.\A is singular matrix. 31) A. 31) b/A The solution to xA = b where x and b are row vectors. 57) importdata Similar to load but there need not be an equal number of elements in each row.(p.(p.(p. 7.(p.(p. 31) B/A The solution to XA = B by Gaussian elimination. 7. Appendix: Reference Tables Input-Output Functions csvread Reads data into MATLAB from the named file. 31) A\B The solution to AX = B by Gaussian elimination.(p.(p.

(p. 120) sprandsym Sparse uniformly distributed symmetric random matrix. n. 22) 153 . the matrix can also be positive definite..(p. (p.0 The transpose of a matrix. . 136. . 95) ones Generates a matrix with all elements being 1. 22) Specialized Matrices hilb Generates the hilbert matrix.) toeplitz Generates a Toeplitz matrix (where the values are constant on each diago- nal. . 22) false Generates a logical matrix with all elements having the value false.(p. 22) rand Generates a matrix whose elements are uniformly distributed random numbers in the interval (0. Gaussian) distributed ran- dom numbers with mean 0 and standard deviation 1. . 120) sprandn Sparse normally distributed random matrix.(p. 1).(p. (p.(p. (p. 28) Elementary Matrix Operations size The size of a matrix.(p. (p.(p. 81.(p. ) length The number of elements in a vector. 120) true Generates a logical matrix with all elements having the value true.(p.(p.(p. 22) numel(A) The total number of elements in a vector or matrix.(p. 22) 0 The conjugate transpose of a matrix. Appendix: Reference Tables Elementary Matrices eye Generates the identity matrix.e.) vander Generates the Vandermonde matrix.(p. 22) rng Generates a seed for the random number generator. 2. 22) speye Generates a Sparse identity matrix. 22) randn Generates a matrix whose elements are normally (i. 22) randperm(n) Generates a random permutation of the integers 1. 22) . (Defined on p.(p. 22) randi Uniformly distributed random integers.(p. 120) sprand Sparse uniformly distributed random matrix. (Defined on p. 95) zeros Generates a zero matrix.

83) deal(x. 100) ipermute The inverse of permute.(p. 38) permute Reorders the dimensions of a multidimensional array. 28) tril Extracts the lower triangular part of a matrix. This is a very dangerous com- mand..(p.e. (p.(p. 28) [] The null matrix.(p. this is useful for putting arrays into a higher-dimensional array. 38) spdiags Generates a sparse matrix by diagonals. 9) diag Extracts or creates diagonals of a matrix. 15. which is frequently the exact value. 154 .(p. 100) triu Extracts the upper triangular part of a matrix.(p. This is also useful for deleting elements of a vector and rows or columns of a matrix.(p.(p.(p. 28) reshape Reshapes the elements of a matrix.(p. y) Reverse two variables. rats Convert a floating-point number to a “close” rational number.(p.(p.(p. 28) squeeze Removes (i. squeezes out) dimensions which only have one element.(p. 28) flipud Flips a matrix up and down. 112) primes(n) Generate the first n prime numbers.(p. 31) tic.(p. Appendix: Reference Tables Manipulating Matrices cat Concatenates arrays. 38) sub2ind Converts the indices of a matrix from matrix form to column vector form.(p. 112) addpath Add to the search path. 120) repmat Tiles a matrix with copies of another matrix. 31) pause Halt execution until you press some key.(p. 28) Odds and Ends path View or change the search path. 28) fliplr Flips a matrix left to right.(p. 28) ind2sub Converts the indices of a matrix from column vector form to matrix form.(p. 112) edit Create a new function or script m-file or edit an already existing one. 15) type Display the actual MATLAB code for a command or function or m-file. (p.(p. 38) clear Deletes a variable or all the variables. toc Return the elapsed time between these two commands. 28) rot90 Rotates a matrix a multiple of 90◦ . 28) bsxfun Performs an operation on a matrix and a vector.(p. 17) cputime Approximately the CPU time (in seconds) used during this session.(p.(p.

(p.(p.(p. 58) ylabel Puts a label on the y-axis.(p. 61) clabel Label contour lines. 58) linspace Generates equally-spaced points.(p.(p. 61) shg Raises the current graphics window so it is visible.(p.(p. 58) hist Plots a histogram. 58) errorbar Plots a curve through data points and also the error bar at each data point.(p.(p. 58) logspace Generates logarithmically spaced points.(p. ) stairs Plots a step function. 58) hold Holds the current plot or release it..(p. 61) view Changes the viewpoint of a 3-D surface plot. 61) contour Plots a contour looking down the z axis.(p. 58) ezplot Generates an “easy”plot (similar to fplot ).(p. x(t).(p. 61) subplot Divides the graphics window into rectangles and moves between them. 58) fill Fills one or more polygons. 58) semilogy The same as plot but the y axis is logarithmic. 61) ezplot3 Generates an “easy” plot in 3-D.(p.(p.(p. 61) surf Plots a 3-D filled-in surface.(p. y) = 0. 66) shg Raises the current graphics window so it is visible.(p.(p.(p.(p. 58) loglog The same as plot but both axes are logarithmic.(p. 61) pol2cart convert polar to cartesian coordinates. 61) ezcontour3 Generates an “easy” contour in 3-D. 58) title Puts a title on the top of the plot. 58) xlabel Puts a label on the x-axis.(p. i. 58) ezpolar Generates an “easy” polar plot. 61) zlabel Puts a label on the z-axis.(p.e.(p. 66) semilogx The same as plot but the x axis is logarithmic. similar to the colon operator.(p.(p. 58) bar Plots a histogram given the number of elements in each bin. i.(p. 58) subplot Divides the graphics window into rectangles and moves between them. 58) axis Controls the scaling and the appearance of the axes. 58) drawnow Updates the current figure. 61) ezsurf Generates an “easy” 3-D filled-in surface. 61) ezcontour Generates an “easy” contour looking down the z axis.(p.(p.(p.(p.(p. 61) contour3 Plots a contour in 3-D. 61) contourf Plots a filled contour. It can also plot a parametric func- tion. 58. 61) ndgrid Same as meshgrid except that the two arguments are reversed. 61) fill3 Fills one or more 3D polygons.(p.(p. 66) colormap Determines the current color map or choose a new one. y(t) . 58) polar Plots the data points in polar coordinates. 58.e.(p. 58) Three-Dimensional Graphics plot3 Plots the data points in Cartesian coordinates. or an implicit function.(p.(p. 61) ezmesh Generates an “easy” 3-D surface using a wire mesh.(p.(p. 61) meshgrid Generates a 2-D grid. Appendix: Reference Tables Two-Dimensional Graphics plot Plots the data points in Cartesian coordinates. 58) 155 .(p. f (x. 61) colorbar Adds a color bar showing the correspondence between the value and the color. 61) axis Controls the scaling and the appearance of the axes.(p. 66) mesh Plots a 3-D surface using a wire mesh.(p..

(p. 66) get Returns the current value of the property of an object. 66) ginput Obtains the current cursor position.(p. 74) uicontrol Create a user interface component.(p. Appendix: Reference Tables Advanced Graphics Features caxis Change the scaling on the color map.(p.(p. 68) gca The current axes handle.(p.(p.(p. 77) getframe Get the current frame. 74) uiresume Resume execution of the GUI.(p. 74) uipanel Create a user interface panel.e. 66) imread Import an image from a graphics file.(p. 66) clf Clear a figure (i. 17.(p.. 77) movie2avi Save the current movie frames to an avi file. 77) saveas Save a figure to disk. 66) legend Places a legend on the plot.(p.(p. 74) uiwait Block execution of the GUI.(p.(p. 66) demo Runs demonstrations of many of the capabilities of MATLAB.(p. 66) figure Creates a new graphics window and makes it the current target. 68) set Sets the value of the property. 66) imwrite Export an image to a graphics file. 77) close Close the file opened with avifile. 77) addframe Add a frame to the avi file. 77) (<avifile>) movie Play movie frames.(p. 77) 156 .(p.(p. 66) image Plots a two-dimensional matrix. 66) text Adds the text at a particular location. (p.(p. 66) fplot Plots the specified function within the limits given.(p. 66) imagesc Plots a two-dimensional matrix and scales the colors.(p. 74) avifile Create a new avi file.(p. 66) imshow Display an image.(p. delete everything in the figure(p.(p. or properties of an object. 68) guide Invoke the GUI design environment to design your own GUI.(p.(p. 68) gcf The current figure handle. 58) gtext Places the text at the point given by the mouse.(p.

43) strcmp Compares strings.(p.(p. 37) min The minimum element of a vector or each column of a matrix.(p. 46) struct Create a structure.(p.(p. ) max The maximum element of a vector or each column of a matrix. 37) prod The product of the elements of a vector or each column of a matrix.(p.(p. 100) strtrim Removes leading or trailing spaces in a string. 93) cell Preallocate a cell array of a specific size. 46) isfield Determine if input is a field name. Structures.(p. 46) getfield Get one or more values of a structure.(p. 48) isa Determine whether a variable is of a particular class. 43) strfind Find occurrences of a substring in a string. 46) fieldnames Return all field names of a structure.(p. 58) bar Plots a histogram when the number of elements in each rectange is known.(p. and Classes num2str Converts a variable to a string. 37) norm The norm of a vector or a matrix.(p.(p. of the elements of a vector or each column of a ma- trix. Appendix: Reference Tables String Functions.(p. 37) sum The sum of the elements of a vector or each column of a matrix. 43) str2num Converts a string to a variable.(p. Alternately.(p. Cell Arrays.(p. it returns a matrix of the same size which contains the larger of the elements in each matrix. 46) class Determine the class of a variable.(p.(p.(p. 46) rmfield Remove one or more fields from a structure.(p. 48) Data Manipulation Commands cumprod The cumulative product between successive elements of a vector or each column of a matrix. if it has two arguments. 46) setfield Set one or more values of a structure. 46) celldisp Display all the contents of a cell array.(p.(p. 37) mean The mean. 37) errorbar Plots a curve through data points and also the error bar at each data point. 46) orderfields Order the fields. or average.(p.(p. 43) sscanf Behaves very similarly to the C command in reading data from a text variable using any desired format.(p. 43) sprintf Behaves very similarly to the C command in writing data to a text variable using any desired format. 37) std The standard deviation of the elements of a vector or each column of a ma- trix.(p.(p.(p. 58) hist Plots a histogram of the elements of a vector.(p. 37) 157 . 37) cumsum The cumulative sum between successive elements of a vector or each column of a matrix. 37) sort Sorts the elements of a vector or each column of a matrix in increasing order(p.

94) >= Greater than or equal to. 95) switch Selects certain statements based on the value of the switch expression.(p.(p. 112) error Displays the error message and terminates all flow control statements. positive definite ma- trix. 91) linsolve Solve a square matrix equation where the matrix can have certain properties to increase the CPU time.(p.(p. 91) rank Estimates the rank of a matrix.(p.(p. 91) null Calculates an orthonormal basis for the null space of a matrix. 91) norm Calculates the norm of a vector or matrix.(p.(p. 93) ˜xor Logical EXCLUSIVE OR.(p. and eigenvectors if desired.(p. 95) elseif Used with the if statement. 95) continue Begins the next iteration of a for or while loop immediately. 93) || A short-circuiting logical OR. 94) < Less than. 91) eigs Calculates some eigenvalues and eigenvectors of a square matrix.(p. 93) | Logical OR. 95) 158 . 112) for Repeat statements a specific number of times.(p.(p. 93) Flow Control break Terminates execution of a for or while loop.(p. 91) Logical and Relational Operators & Logical AND. 91) eig Calculates the eigenvalues.(p.(p. 95) otherwise Part of the switch command. 93) && A short-circuiting logical AND.(p.(p. 94) <= Less than or equal to. 95) case Part of the switch command. 80) lu Calculates the LU decomposition of a square invertible matrix. 94) = Not equal to.(p. 91) rref Calculates the reduced row echelon form of a matrix.(p.(p. 83) qr Calculates the QR decomposition of a matrix.(p. 95) else Used with the if statement. 80) svd Calculates the singular value decomposition of a matrix. 95.(p. 95) if Executes statements if certain conditions are met. 91) orth Calculates an orthonormal basis for the range of a matrix. 93) Logical NOT.(p.(p. 91) det Calculates the determinant of a square matrix.(p. 91) cond Calculates the condition number of a matrix.(p.(p.(p. if.(p. of a square matrix. 91) condest Calculates a lower bound to the condition number of a square matrix. Appendix: Reference Tables Some Useful Functions in Linear Algebra chol Calculates the Cholesky decomposition of a symmetric.(p.(p.(p. 95) while Repeats statements as long as an expression is true. switch.(p. 94) > Greater than. 91) pinv Calculates the pseudoinverse of a matrix. 94) == Equal. 93) ˜ strcmp Comparing strings.(p. 91) inv Calculates the inverse of a square invertible matrix. and while statements.(p.(p.(p.(p.(p.(p. 95) end Terminates the scope of the for.(p.

100) isinf Generates a matrix with 1 in all the elements which are Inf and 0 other- wise.(p. 100) Programming Language Functions echo Turns echoing of statements in m-files on and off.(p. 112) eval Executes MATLAB statements contained in a text variable.(p.(p.(p. 95.(p. operates on the columns of a ma- trix. 114) feval Executes a function specified by a string. 100) islogical True for a logical variable or array.(p. 114) function Begins a MATLAB function. 112) global Defines a global variable (i.e. 112) varargin “Groups” input arguments together. 100) isnan Generates a matrix with 1 in all the elements which are NaN and 0 other- wise. 112) return Terminates the function or script m-file immediately. 100) logical Converts a numeric variable to a logical one.(p.(p. operates on the columns of a ma- trix.(p.(p. []. 100) isequal Tests if two (or more) arrays have the same contents. it is contained here.(p.(p. 112) error Displays the error message and terminates the function.e.(p. 112) lasterr If eval “catches” an error. (p.(p.(p. 112) end Ends a function. i. 100) exist False if this name is not the name of a variable or a file.(p. 112) varargout “Groups” output arguments together. 106) nargin Number of input arguments supplied by the user.(p. 106. Appendix: Reference Tables Logical Functions all True if all the elements of a vector are true..(p.(p. 100) any True if any of the elements of a vector are true. 114) persistent Defines a local variable whose value is to be saved between calls to the func- tion.(p.(p. 112) 159 . 100) isempty True if the matrix is empty. Only required if the function m-file contains a nested func- tion.(p.(p. it can be shared between different functions and/or the workspace).(p.(p.e. not Inf or NaN ) and 0 otherwise. 100) isfinite Generates a matrix with 1 in all the elements which are finite (i. 112) keyboard Stops execution in an m-file and returns control to the user for debugging pur- poses. 112) nargout Number of output arguments supplied by the user.. 100) ischar True if a vector or array contains character elements.. 100) find The indices of a vector or matrix which are nonzero.

106) dbcont Continue execution. Appendix: Reference Tables Debugging Commands keyboard Turns debugging on. 147) idst The inverse discrete sine transform.(p.(p. 120) spy Plots the locations of the nonzero elements of a sparse matrix. 147) ifft The inverse discrete Fourier transform. 106) return Quit debugging mode and continue execution of the function. 120) find Finds the indices of the nonzero elements of a matrix. including the line numbers.(p. 106) dbstop Set a breakpoint. 120) full Converts a sparse matrix to a full matrix.(p.(p.(p. 106) dbdown Change the workspace down to the called function.(p. 120) spconvert Generates a sparse matrix given the nonzero elements and their indices.(p.(p. 106) dbup Change the workspace to the calling function or the base workspace. 120) sprandn Sparse normally distributed random matrix.(p. 106) dbtype List the current function.(p. 147) dst The discrete sine transform. 147) fftshift Switches the first half and the second half of the elements of a vector.(p. 106) dbstatus List all the breakpoints.(p. 106) dbstack Display all the calling functions. 106) dbquit Quit debugging mode and terminate the function.(p. 120) nnz Returns the number of nonzero elements in a matrix.(p.(p.(p.(p.(p. 120) spdiags Generates a sparse matrix by diagonals.(p.(p. 120) sparse Generates a sparse matrix elementwise. 106) dbstep Execute one or more lines. 120) spfun Applies the function to a sparse matrix. 147) Sparse Matrix Functions speye Generates a Sparse identity matrix.(p. 147) fftshift Unswitches the first half and the second half of the elements of a vector.(p. 106.(p.(p.(p. 112) Discrete Fourier Transform fft The discrete Fourier transform. 106) dbclear Remove a breakpoint. 120) sprand Sparse uniformly distributed random matrix.(p.(p.(p. 120) 160 .

(p.(p.(p. variable-order. 122) ode23t Stiff ode solver.(p.(p. (p. Appendix: Reference Tables Time Evolution ODE Solvers ode45 Non-stiff ode solver.(p. second-order. one-step method. second-order. 140) fminbnd Numerically calculates a local minimum of a one-dimensional function. 140) optimset Allows you to modify the parameters used by fzero. (p. fourth-order. 122) ode23s Stiff ode solver. 140) 161 . variable-order. and fminsearch. y0 ) = 0. 122) ode15i Stiff ode solver. second-order. multi-step method for the fully implicit ode f(t. one-step method. 135) bvpinit Calculates the initial guess either by giving y directly or by using a function y = initial guess function(x). (p. one-step method for the ode y0 = f(t. trapezoidal method.(p. 122) ode113 Non-stiff ode solver. 122) ode23 Non-stiff ode solver. 135) Numerical Operations on Functions dblquad Numerically evaluates a double integral. The interval can be infinite and/or the function can have an integrable singular- ity. 135) deval Interpolate to determine the solution desired points.(p. y. b] with given boundary conditions and an initial guess for y.(p.(p.(p. 122) ode15s Stiff ode solver. 140) quad Numerically evaluates an integral using Simpson’s method. 140) fminsearch Numerically calculates a local minimum of a multi-dimensional function.(p. 135) bvpset Assigns values to properites of bvp4c. 126) Boundary-Value Solver bvp4c Numerically solves y0 (x) = f(x.(p. multi-step method. variable-order.(p. 140) fzero Numerically calculates a zero of a function. fminbnd. (p. 131) odeset Assigns values to properties of the ode solver. 122) ode23tb Stiff ode solver. (p. 140) quadl Numerically evaluates an integral using the adaptive Gauss-Lobatto method. y).(p. one-step method. y) for x ∈ [a. 140) quadgk Numerically evaluates an integral using the adaptive Gauss-Kronrod method.(p. multi-step method.

137) polyder Calculates the derivative of a polynomial.(p. 148) sqrtm Matrix square root.(p. 137) interp3 Does three-dimensional interpolation. 137) interp2 Does two-dimensional interpolation. 148) 162 . (p.(p.(p. 137) spline Cubic spline interpolation. 137) ppval interpolates a piecewise polynomial calculated by pchip or spline.(p.(p.(p.(p. 148) funm Evaluate general matrix function. 137) pchip Cubic Hermite interpolation. 137) roots Numerically calculates all the zeroes of a polynomial.(p. 148) logm Matrix logarithm.(p. 137) poly Calculates the coefficients of a polynomial given its roots.(p.(p. Appendix: Reference Tables Numerical Operations on Polynomials interp1 Does one-dimensional interpolation.(p.(p. 137) polyval Evaluates a polynomial at a point. 137) polyfit Calculates the least-squares polynomial of a given degree which fits the given data.(p. 137) polyder Calculates the integral of a polynomial.(p. 137) polyvalm Evaluates a polynomial with a matrix argument. 137) Matrix Functions expm Matrix exponentiation.

1i*12 20) (1/3) answer: 1. 2 % or x = [0:30].1a) >> A = [1 2 3 4.3) >> th = input( 0 th = 0 ).1751 ˆ ˆ b) >> format long >> c answer: 6.tril(A. 9:12.1a) >> a = 3.7. 13 14 15 16] >> A = [1:4. 2) .5 % or C = sqrt(A) ˆ b) >> A .7.10. A(1.:) 2.-1) 2.9.2*a*b*cosd(ab)) answer: 6. B 2 >> A - ˆ C.1) = 5.3637e+07 .5) >> x = [0:30] 0 . and 4.4) zeros(6) ]. deg = pi/180.6. 1 ) . 5 6 7 8.10.3) >> A = diag([1:n]. 4 5 6.10. 2.9.7.10. -1 ) 2.4) help fix or doc fix.9.7.9.6850e+06i ˆ ˆ 1.2) >> (1.10. 7 8 10] >> B = A .diag( ones(n-1.10) = -5 b) >> A = A .175085147187636 c) >> format short e >> asin( (b/c)*sin(ab*deg) ) / deg or >> asind( (b/c)*sind(ab) ) answer: 4.diag( ones(n-1. .1) ˆ 1. 9 10 11 12. 5:8.2*a*b*cos(ab*deg)) or ˆ ˆ >> c = sqrt(a 2 + b 2 .ans 0 1. A(6. 1 ) .10. 1.10.1).2) >> A = 4*eye(n) . ab = 79.7a) >> A = [1 2 3.9. im] = max(R 0 ) c) >> mean(mean(R)) % or mean(R(:)) d) >> S = sin(R) e) >> r = diag(R) 2.:) + A(3. Solutions To Exercises These are the solutions to the exercises given in subsections 1.diag( ones(n-1.5 % or B = sqrtm(A) >> ˆ C = A.1). 2. -1 ) ˆ 2.diag( exp([2:n]). >> c = sqrt(a 2 + b 2 . 2 0 ˆ ˆ 2.10. 3.1).4a) >> A = [ ones(6. 2 ˆ 163 .9448e+01 0 d) >> diary triangle.2e20 .:) = (-9/5)*A(2. 13:16] >> A = [ [1:4:13] 0 [2:4:14] 0 [3:4:15] 0 [4:4:16] 0 ] b) >> A(2.(2*cos(th) 2 . b = 5. cos(2*th) .6a) >> R = rand(5) b) >> [m.

1) >> hold off >> plot(x.* sin(2*pi*X) .serial number = s1. y-z. >> y = x. z) c) >> plot(x.2} 2 >> c{2.3}= c{1.serial number = 1 >> s2 = struct( 0 name 0 . >> plot(x. 100). z.7.* cos(x .6.6.1}= uniform 0 >> c{1. >> y = exp(x). 0 r 0 . y-z) 4. 0 bandit 0 .2}= pi 10 >> c{2. 6 /6 >> hold on ˆ ˆ >> plot(x.1).6. 0 r 0 . 0 Alfonso Bedoya 0 .serial number + 1 3.1}(1.2}(5) 3. Y] = meshgrid(x. 0 m0 ) >> axis equal >> xlabel( 0 x 0 ) >> ylabel( 0 y 0 ) >> title( 0 e i\pi = -1 is profound 0 ) ˆ e) >> subplot(2.2a) >> x = linspace(-3. +1.3a) >> f = @(x./(abs(x(1) + x(2)) + 1) c) >> f = @(x) (cos(x) . z. >> [X. y) b) >> z = 1 + x + x.2) >> c{2.* sin(2*pi*Y). Z).7. 1.rank = 0 bandit 0 >> s1. y). >> Z = (X. 1. 91). Y. 2 /2 + x. Y] = meshgrid(x. 3.1}= rand(5) 0 >> c{2. >> ˆ surf(X. 2) .2a) >> c{1. 2) >> plot(x.name = 0 Alfonso Bedoya 0 >> s1.3}= true ˆ b) >> c{1.y) b) >> f = @(x) x(1) .*(heaviside(x) .y) sin(x + y) . % or just do [X. ˆ 164 . x. y-z) d) >> hold off >> plot(x. y.exp(x(2) + cos(x(3). Solutions To Exercises 3.heaviside(x .2}= ˆ @(x) sin(exp(x)) >> c{1. 0 g 0 . x). y. x. x. 0 g 0 ) >> axis equal >> xlabel( 0 x 0 ) >> ylabel( 0 y 0 ) >> title( 0 e i\pi = -1 is profound 0 ) >> ˆ subplot(2. 1) >> s1.1) >> s1. 2 + 4* Y.1a) >> x = linspace(-1.2*pi)) 4. 0 rank 0 . 0 serial number 0 .

t). ci . meshgrid then turns these vectors into a mesh so that h(xj . 165 . j)th element is ai . We can consider these to be the horizontal P and vertical n axes in two dimensions. (Since the matrices X and C never change. t). t) ) is a matrix whose (i. t) = k=1 h(x. t) is evaluated by h(X(i. The sum command then adds all the rows in each column.) Thus. C. Solutions To Exercises b) One particular choice is >> view([1 2 5]) % or view([63 66]) 4.7. j). t) = f (x − ct) so that g(x. whose (i. where i refers to the vertical axis and j the horizontal one. This is done by multiplying the matrix R. they would not need to be actual arguments to h. j)th element is f (xj − ci t). h(t) (short for h(X. t). We define h(x. C. c is a column vector of the speeds.3) x is a row vector containing all the points at which the function is to be evaluated. j). We need to multiply this by ai and then sum over i. c. ck . C(i. elementwise by the matrix h(X.

Solutions To Exercises 166 .

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 167 . Comma 154 108 l 055 45 . Minus sign or dash 155 109 m 056 46 . 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 . 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 .

The first 32 codes (numbers 0–31 decimal) as well as the last (number 127 decimal) are non-printing characters which were initially intended to control devices or pro- vide meta-information about data streams. 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. 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. ˆ 168 . ASCII Table with a description of the character symbol.

13. 133. 13. 36. 64. followed by symbols. 152. 13. 66. 151 addframe. 13. 133. 27. 59. 151 asecd. 13. 46. 13. 135. 157 deal. 36. 47. 14. 158 dbstatus. 59. 98. 158 chol. 13. 157 dbclear. 151 clf. 100. 151 clear. 13. 77. 3. 38. or in the reference tables in the appendix. 161 169 . 112. 37. 95. 13. 160 ceil. 47. 161 bvpinit. 151 conj. 151 condest. 13. 64. 151 cotd. 16. 14. 158 addpath. 152 axis. 36. 151 atand. 105. 49. 95. it is underlined. 66. this is indicated as well as the page number (in parentheses). 155 cumprod. 160 different than in C. 90. 151 asech. 106. Index In this index MATLAB commands come first. 151 colorbar. 151 atanh. 151 colormap. 151 asec. 44. 151 close. 81. 160 bsxfun. 95. 37. 160 caxis. Only then does the index begin with the letter “A”. 47 det. 13. 140. 65. 135. 151 cscd. 61. 13. 66. 55. 12. 106. 77. 61. 90. 46. 13.e. 154 dbdown. 86. 126 cumsum. 151 cot. 101. 86. 156 dbtype. 151 atan2. 155 acsc. 9. 48. MATLAB functions clabel. 106. 8. 57. 151 coth. 13. 13. 133. 157 ballode. Note: When an item appears in a box at the end of a subsection. 13. 61. 85.. 151 contourf. 8 acosh. 151 asind. Note: If an item is a primary topic of a section. 24. 61. 37. 77. 63. 106. 160 cell. 158 acscd. 154 contour. 161 dbquit. 151 asin. 151 csvread. 159 contour3. Note: All words shown in typewriter font are MATLAB commands or predefined variables unless it is specifically stated that they are defined locally (i. 58. 156 acot. 13. 64. 155 all. 66. 13. 106. 132. 63. 106. 55. 158 dbcont. 160 break. 13. 151 asinh. 150. 154 dbstop. 154 acosd. 17. 155. 160 bvpset. 151 cond. 36. 59. 13. 161 dblquad. an appendix. 63. 99. 160 bvp4c. 158 deval. 157 demo. 13. 83. 90. 57. 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. 28. 59. 159 cos. 13. 61. 83. 13. 151 cosh. 34. 14. 13. 156 char. 85. 151 cputime. 155 any. 44. 155 angle. 106. 66. 151 cosd. 157 bar. 13. 151 dbup. 155 class. 151 classdef. 156 continue. 160 case. 100. 52. in this document). 151 csch. 134 dbstack. 63. 13. 152 avifile. 31. 154 celldisp. 55. 95 dbstep. 106. 61. 156 csvwrite. 90. 157 abs. 106. 155 acoth. or a subsection. 106. 156 acotd. 154 atan. 48 acos. 151 csc. 135. 151 danger in using. 13. 160 cat. 158 acsch.

4. 159 interpn. 138. 13 imshow. 17. 157 ifftshift. 107. 14. 85. 67. 52. 120. 152 getfield. 155 int32. 155 isequal. 65. 83. 64. 152 fscanf. 155 int16. 87. 58. 159. 12. 158 length (number of elements in). 153 format. 16. 92. 143. 154 fieldnames. 10. 156 eye. 150 eig. 156 exp. 25. 100. 11. 98. 95. 12. 58. 159 help. 48 image. 155 input. 66. 151 function. 160 isfield. 95. 92. 57. 152 legend. 84. 117. 159 flipud. 151 interp1. 160 log. 140. 14. 53. 100. 155 inline. 85. 156 diary. 94. 113. 24. 42. 159 log10. 156 doc. 56. 162 fft. 62. 120. 154 helpbrowser. 13. 66. 161 lasterr. 85. 145. 66. 151 events. 152 interp3. 100. 98. 159. 95. 8. 155 fprintf. 156 ezcontour. 97. 60. 161 keyboard. 90. 158 hist. 151 echo. 13. 23. 58. 156 logspace. 65. 100. 47 ezplot3. 160 fminsearch. 158 error. 46. 156 ischar. 64. 56 full. 158. 66. 100. 119. 13. 55. 160 eval. 68. 158 idst. 137. 99. 156 exist. 51. 147. 2. 159 find. 140. 91. 159 fopen. 105. 153 imwrite. 48. 160 errorbar. 143. 105. 90. 58. 61. 143. 13. 15. 66. 156 dst. 46. 147. 148. 83. 25. 143. 36.6 (32). 112. 14. 28. 162 imread. 140. 23. 114. 62. 60. 13. 114. 150. 156 logm. 23. 61. 148. 95. 160 ipermute. 139. 137. 100. 20. 155 gca. 117. 55. 100. 62. 74. 156 linspace. 83. 113. 159 fminbnd. 16. 159 floor. 66. 114. 145. 17. 150 linsolve. 11. 107. 103. 100. 156 for. 41 ezmesh. 155 guide. 153 eigs. 77. 100. 152 load. 8. 157 figure. 43. 16. 106. 159 double. 10. 153 interp2. 159 fzero. 155 170 . 66. 154 get. 47 factorial. 155 int64. 4. 112. 156 drawnow. 47 gtext. 93. 68. 156 disp. 152 expm. 60. 33. 49. 112. 151 importdata. 159 imagesc. 105. 97. 157 fix. 112. 47. 85. 55. 41. 159 imag. 63. 61. 162 false. 114. 109. 28. 137. 67. 113. 150 global. 147. 155 int8. 61. 100. 147. 150 edit. 66. 15. 78. 65. 160 inv. 84. 138. 68. 100. 152 be careful. 15. 61. 60. 9. 65. 159 if. 87.diag. 57. 160 end. 58. 66. 32. 158 fftshift. 157 else. 55. 22. 159 fill3. 98. 155. 147. 154 ezcontour3. 151 isnan. 68. 58. 36. 158 hilb. 162 feval. 80. 95. 158 hold. 157 diff. 156 expm1. 47 ezpolar. 137. 59. 161 loglog. 6. 13. 84 ginput. 22. 90. 58. 65. 16. 159 fill. 152 ezplot. 54. 84. 66. Subsect. 88. 147. 147. 38. 158. 43. 160 heaviside. 20. 100. 13. 91. 17. 65. 158 fplot. 53. 37 getframe. 94. 32. 47 log1p. 154 islogical. 102. 13. 99. 162 logical. 46. 155 elseif. 151 funm. 66. 151 function handle. 154 isinf. 95. 53. 101. 97. 47 ezsurf. 157 isa. 54. 29. 162 fclose. 109. 148. 86. 155 ind2sub. 66. 155 isempty. 58. 55. 112. 58. 118. 63. 108. 162 gcf. 7. 155. 151 isfinite. 28. 47. 159 ifft. 93. 159 fliplr.

21. 17. 162 std. 20. 157. 37. 43. 156 ode15i. 162 spconvert. 54. 137. 157 rem. 135. 67. 154 sort. 162 sqrt.lookfor. 13. 38. 122. 43. 154 spdiags. 90. 16. 154 norm. 60. 61. 160 persistent. 150 strtrim. 112. 58. 46. 140. 159 rmfield. 137. 162 squeeze. 151 polyfit. 155 ode23t. 43. 155 sprandsym. 139. 13. 158 speye. 34. 13. 153 saveas. 153 max. 161 sind. 119. 137. 57. 59. 100. 120. 155 rank. 151 ode15s. 160 line properties. 148. 61. 61. 154 polyval. 96. 20. 106. 158 num2str. 153. 105. 161 semilogx. 157 profile. 37. 61. 160 polyder. 120. 13. See Line properties spline. 109. 158 sub2ind. 154 sparse. 137. 35. 63. 21. 161 surf. 54. 58. 160 plot. 103. 97. 37. 61. 46. 158 round. 61. 162 sqrtm. 13. 26. 13. 158 meshgrid. 161 shg. 157 polyvalm. 120. 51. 61. 48 struct. 56. 160 nargin. 112. 151 orderfields. 103. 90. 157 print. 153 mean. 16. 131. 28 movie. 155 sprintf. 155 171 . 160 permute. 90. 43. 28. 153 mesh. 137. 53. 136. 60. 81. 122. 59. 102. 158 randi. 137. 90. 155 spfun. 158 sinh. 154 quad. 22. 90. 137. 117. 136. 48 real. 107. 22. 58. 22. 21. 89. 58. 120. 158 prod. 137. 77. 154 methods. 162 sscanf. 112. 59. 50. 53. 158 size. 126. 45. 35. 119. 120. 95. 112. 157 pause. 151 ode23. 83. 29. 20. 159 rng. 53. 155 ppval. 83. 161 sum. 54. 46. 47. 139. 154 str2num. 122. 77. 151 null. 152 strcmp. 150 numel. 139. 66. 153 sin. 157 strfind. 13. 161 sech. 112. 24. 122. 120. 22. 157. 36. 155 roots. 157 primes. 135. 156 ode45. 161 sign. 101. 157 qr. 89. 159. 118 pinv. 75. 22. 157 single. 35. 135. 157 randperm. 101. 114. 154 movie2avi. 153 polar. 151 min. 37. 76 sprand. 151 ode23s. 61. 161 secd. 136. 156 odeset. 155 rats. 153 ndgrid. 158 rref. 161 set. 155 quadgk. 68. 37. 52. 161 sec. 120. 130. 103. 58. 37. 77. 111. 119. 157 poly. 161 semilogy. 137. 155 sprandn. 118. 13. 160 rot90. 46. 120. 5 (77). 140. 130. 28. 162 using set rather than plot. 160 plot3. 14. 117. 84. 150 rand. 138. 162 polyint. 22. Sect. 155. 153. 157 quadl. 153. 38. 157 properties. 151 ones. 20. 160 pol2cart. 134. 119. 97. 58. 118. 90. 17. 122. 22. 112. 88. 155 ode23tb. 159 differences from diag. 60. 26. 55. 157 randn. 157 ode113. 58. 136. 34. 125. 100. 156 return. 160 pchip. 119. 88. 153 path. 122. 151 otherwise. 140. 93. 151 mod. 162 nnz. 13. 161 setfield. 52. 161 subplot. 136. 157 save. 37. 104. 22. 153 lu. 43. 20. 122. 47 orth. 151 optimset. 90. 162 stairs. 135. 13. 45. 137. 57. 120. 140. 120. 156 reshape. 13. 89. 63. 36. 82. 157 nargout. 37. 151 repmat. 59. 42. 49. 162 spy. 80.

158 >=. 96. 31. 13.. 15 . 94. 110 ylabel. See Transpose . 17. 7. 15. 62. 115 xlabel. 152 0ˆ. 158 tanh. 11 <. 82./. 31. 104 xor. 28. 158 title. 31. 149 principle. 62. 93.. 64 uint8. 69 /. 28. 54. 155 nlode (boundary value ode). 152 nlode y ic (initial conditions for nlode). 67. 18. 133 nlode all (boundary value ode). 150 uicontrol. 146 uiwait. 158 acos. 6. 2. 14. 156 colormap example (modifying the colormap). 70. 93. 158 tan. 67. 155 . 74. 158 gravity ode (force of gravity example). 153 []. 93. 151 ˜ &. 13.3 (23). 10 :.2 (22). 96. 152 vdp ode (van der Pol’s ode). 156 fibonacci (recursive code for Fibonacci series). 132 zeros. 140 ↑ up-arrow key. 158 different than in C. 159 138 varargout. 16. 137. 154 ||. 19. 108.svd. 41 get intervals slowly (non-vector operations view. 134 Symbols nlode bc (boundary conditions for nlode). 70. 152 spruce (example using optional arguments).*. 54. 25. 17. 152 A ˆ . 158 nested ex (example of nested functions). 151 =. 108. 2. 61. 156 fft ex3 (Fourier transform example). 15. 102 . 155 myheaviside (the Heaviside function). 154 ˜ !. 23. 156 fft ex2 (Fourier transform example). 130 who. 28. See Conjugate transpose . 34. 15. 78. 13. 158 switch. 74. 22. 67. 151 . 109. 79. 59. 154 tril. 95 ==. 93. 150 hilb2 (calculating Hilbert matrix). 152 running gaussians (plot Gaussians in time). 25. 149. 158 text. 29 sample movie (example making movie). 31. 149. 149. 23. 96. 29. 93. 153 nlode1 (boundary value ode). 156 |. 94. 47 duffing ode (Duffing’s ode). 52 warning about matrix division. 94. 149 abs. 158 toc. 7. 132 +. 30. 63. 95. 149 A+ . 155 example). 28. 94. 66. varargin. 61. 7. 31. 28. 133 exception to. 149. 18. 20. 31.. 29. Subsect.. 58. 13. 9. 7. 112. 74. 28. 31. 29. 116 while. 28.. 150 hilb local (calculating Hilbert matrix). 153 AT . 123 uint32. 153 fzero example (Calling fzero using a nested function). 16. 75 . 59. 151 <=. 133 zlabel. 149 Accuracy. 95. 30. 112. 7. 149. 9. 90. 28. 7. 103 \. . 132 nlode bc2 (boundary conditions for nlode). 158 tic. 155 nlode2 (boundary value ode). 96. 94. 158 >. 95. 93. 28. 124 uint64. 154 @. 13. 152 . 93. 149 Abort current statement. 93. 102 whos. 16. 72 *. 7. 93. 62. 30 pause rippling (GUI example).\. 47 duffing p2 (Duffing’s ode). 128 . 93. 94. 22. 149. 28. 136. 158 tand. 31. 7. 40 triplequad. 6. 19. 31. 153 Local m-files in companion zip file type. 117 vectorize. 47 duffing closure (Duffing’s ode). 152 pause rippling2 (GUI example). 30. 149. 67. 70 -. 158 acosd. 17. 149 triu. 152 prealloc (example of preallocating arrays). 112 vander. See Matrix. 31. Subsect. 0 . 152. 26. 19. 83. 31. 151 172 . 94. 58. 74. 159 get intervals fast (vector operations example). 151 &&. pseudoinverse of %. 152 rippling (plot surface in time). 58. 146 uiresume. See factorial toeplitz. 7. 23. 7. 25. 22. 101. 54. 29. 47 fft ex1 (Fourier transform example). 149. 154 true. 152. 153 AH . 145 uipanel. 94. 13. 31. 124 uint16.

135. 77–80 Class.acosh. 43 asec. 98. 126 danger in using. 152 caxis. 67 subclass. 14. 29 cat. 155 atanh. 83. 7. 38. 9. 99 concatenating. 8. 42. 29. 151 multiline. 161 all. 152 Calculator. 151 Cholesky decomposition. 44. 159 15. 44. 31. 90. 13. 40. 55. 107. 7. 46. 161 acscd. 45. Sect. 42. 1. 48 avifile. 85. 135. 149. 13. 13. 47 Axis handle. 29. 158 -. 157 Clear (a figure). 28. Subsect. 132. 151 find substring in. 30 char. 8 bar. 152 cell. Subsect. 30. 7. 154 ballode. 156 . 161 AND (logical operator). Subsect. 2. 43. 78. 85 atand. 161 angle. 31. 27. 151 \. 149. . 151 continuation method. 22 ˆCC. 13. 151 break. 2 (17) Character string. 151 44 asinh. 13. 151 chol. 28. 151 (131). 31. 64.(programming language). 47. 59. 85. 157 Augmented matrix form. 82. 93. See Initial-value ordinary differential See also clf and close 173 . 151 Bessel's equation (cont. 52. 149. 48 Ball. 7. 61. 40. 152 Case sensitive. asind. 7. 113 *. 62. 7.1 (6). Subsect. Sect. 157 ˆ elementwise. 9 warning about matrix division. 42 ASCII character representation. 13. 30. 152. 150 Arithmetic progression. 3. 7. 1. 156 bsxfun. 101. 149 C++ (programming language). 134 acsch. Subsect. 94. 156 fundamental. 96. 152 Cell array. 13. 13. 158 addframe.4 83. 46. 151 TEX commands in. 151 Binary format. 95. 46 axis. 67 listener. 48 Average value. 8. 149. 35 event. 36. 152 different than in C. 158 bvpset. Arithmetical operations. 58. 31. 133. 61. 66. 66. 151 equations acotd. 67 atan. 135. 13. 95. 62. 100. 13. 92 equal (are two arrays). 29. 158 atan2. 13. 37. 3. 13. 95 /. 99. 99 ˆ. 34. 46. 30 case.\. Subsect. 151 Boundary-value ordinary differential equations. 149. 112. 47. 150 any. 77. 54 . 31. 28. 47 Array. 134. 7. 31. 94. 31. 151 class. 149. 95. 149. 152 equal (are two cell arrays).) acot. 48 user-defined. 13. 128–130 clear. 154 . 31. 100. 9. 155./. 8. 157 (28).3 (42). 77. 84. 47 B value. 113 +. 152 Catching errors. 13. 29. 29. 154 addpath. 133. 48. 23. 113 asecd. 28. 155 fundamental (table). 17. 157 . 97 asech. 42 Vector and Cell array comparing strings. 45. 16. 167 converting to. 55. 65. 149. See Function C ans. 11 acsc. 79. 151 clabel. 36. 48 changing numbers on.5 (46) See also Matrix callback. 157 See also Matrix and Multidimensional arrays and appending to. 13. 151 putting a number of strings in lexicographical ordering. 31. 154 bvp4c. 152 ceil. 43 asin. 48 tick marks outside plot. 151 executing. 12. 151 Anonymous functions. 135.*. 56 acoth. 159 bvpinit. 63 Bessel’s equation. 3.1 (6) exception to.4 (43). 30. 152 celldisp. 48 classdef. 31.

106. 151 See also disp and fprintf cosh. 160 Command. 37. 61. 58. Subsect. 17. 61. 36. 66. See Fourier transform contour3. 90. 49 dblquad. 106. 160 possible floating-point errors in. 37 Continuation method. 90. 55. 13. 59 Discrete sine transform. 93. 106. 87 Eigenvectors.3 (23). 6. 14. 151 diag. 36. 16. 23. 23. 81. 65 dbclear. 57. 24. 152 See also Machine epsilon writing from MATLAB. 151 suppressing. Subsect. 151 doc. 140. 32. 160 colormap. 94. 57. 62 eig. 3. 84 cosd. 149 dbdown. 155 dbstep. 13. 3 dbtype. 9. 160 csc. 31. 64. See RGB components dbstop. 83. 87. 36. 106. 134 Digits of accuracy. 9.8 (34). 155 dbstatus. 14 Debugging m-files. 95. 91. 160 Color map. 151 csvread. 84 eps. 84 elseif. 147. 106. 160 See also Function dbup. 149 deal. 160 Colon operator. 154 Conjugate transpose. 13. 49. 156 Conchoid of Nicodemes Demonstration program. 1. 17. 83. 103 D definition of. 158 manipulation. 31 drawnow. 157 end. 83. 158 Determinant. 86 Condition number. 6. 13. Subsect. 9. 151 Documentation (MATLAB). 47 Clown. 1. 55. 10. 157 Earth. 151 Duffing’s equation. 2. 43. 15. 15. 138 fundamental (table). 151 differential equations csch. 150 reading into MATLAB. 106. 158 disp. 95. 158. 161 conj. 8. 83. 10 continue. 124. 160 Comment character. 61. 135. 64 dbstack. 2. 93. Subsect. Subsect. 151 double. 13. 94. 156 fundamental Closure. 155 Discrete Fourier transform. 158 closing files. 13. 152 Erase (a figure). 3. 61. 119. 159 Cursor edit. 106. See Fourier transform Contour plot. 14. 161 See also linspace dbquit. 2. 105. 61. 155 formatting the. See Matrix See also Transpose diary. 158 best polynomial fit to. 59.2 (22). 105. 32. See Function m-file and Script m-file Complex numbers. 112. 85. 28. 66. 63 174 . 155 Display contourf. 64.5 (46) close. 152. 152 E csvwrite. 52. 63. 95. See Interpolation ez . 154 dst. 158 det.6 (32) cos. 90. 155 cputime. 150. 40. 112. 87. 103. 154 entering current position. 106. 19 Diagonals. 14 cumprod. 55. 157 echo. See Matrix deval. 66. 57. 7. 65 cumsum. 4.clf. 63. 109.6 (13) demo. dbcont. 57. 7. 16. 149 diff. 154 Complex conjugate. 160 28. 18. 65 cond. 103 Data eigs. 24. 86. 13. 86. 90.4 (10) Control flow. 92. 160 colorbar. 85. 83. 158 condest. 9. 63. 59. 28. 150 cot. 63. 108. 90. 3. 135 else. 133. 13. 159 opening files. 90. See Initial-value ordinary cscd. 151 Dot product. 13. 47 CPU. 160 Colors. 106. 16. 90. Subsect. 152 Cubic splines. 15. 77. Subsect. 14 variable. 152 Continuation (of a line). 30 coth. 15. 95. 66. 55. 156 Data types. 16 cotd. See Programming language misinterpreting. 158 Eigenvalues. 106. 87. 8. 16. 149 cos z. 19. 63. 37. 2. 87. 59. 84 contour.

Erase (a .

95. 160 ezplot3. 101 fieldnames. 11. 118. 83. 155 commands in.3 (100) format. 9. Sect. 41 Floating-point operations. 158. 139. 105. 25. 159 printing a matrix. 100. 14 (140) errorbar. 53. 60. 84 expm. 6. 61. 48 fplot. 60. 61. 15. 112. 84 recursive. 159 real. 106. 150 names of. 159 fclose. 156 name of. 147. 117. 29 specifications (format). 141 error. Subsect. 23. 112. 155 debugging. 43. 106. 106 fftshift. 10. 66. 152 inline. 119. 41 fft. 161 Function handle. 84 Extrapolation. 108 floor. 55. 13 fscanf. 84. 66. 53. 60. 147. 12. 41 feval. 95. 85. 58. 3. 160 input and output arguments. 159. 113. 22. 151 specifications (format). 112. sprintf. 145. 91. 155 anonymous. 108 fminsearch. 85. 40. 156 EXCLUSIVE OR (logical operator). 101. 108. 83.3 (100) ezcontour. 16 ezplot. 152 Exponentiation. 155 nested. 20. 160 See also Interpolation function. 160 Euclidean length. 46 fopen. 112 pass by reference. 46 ezcontour3. 25. 157 variable number of. Subsect. 109 factorial. 12 ezsurf. 155 warning. 159 warning. 148. 10. 61. 13. Subsect.1 (40). 55. 101. 15 fill3. 2. 151 private. 138. Sect. 23. 13. 84. 143. 47 for. 14. 83. 85. 112. fscanf. See Flops primary. 102. 101 ezpolar. 114. 36 111 fix. 11 error. 146 eval. 96. 120. Sect. 85. 160 Flow control. 100.) Fourier series (cont. 13. 58. 102. Subsect. 154 passing function name in argument list. 147. 136 full. 104. See Structure pass by value. 144 events. 162 Frequency. 102 figure. 100. 159 eye.) See also clf complex. 42. 161 subfunctions in. 104. 11. 66. 160 order in which MATLAB searches for functions. 101. 54. 84 exp. 155 conflict between function and variable name. 140. 158. 154 (41). FALSE (result of logical expression). Subsect. 30 return. 114 Floating-point numbers. 8. 108 Fibonacci sequence. 153 Function. 147. 93 103 Fast Fourier transform. 64. 140 Error bars.2 flipud. 159 fast (FFT). 155. 61. 114. 28. 3 end statement. 159 false. 151 passing arguments indirectly. See Fourier transform function (required word). 152 function handle. 8. 113. See Programming language saving parameters in. 61. 155 warning about user-defined m-files. 94. 140. 94. 42 sscanf). See Power expm1. 3. 158 Function m-file. 64. 158 fprintf.6 (32). 105 definition line. 100 F differences from command. 59. 105 Format options (in format command). 11. 97. 111 Fourier series. 84. 14 (140) Functions (mathematical) 175 . 109 find. 157 discrete. 159. 15. 155 built-in. 152 exist. 108. 120. 55 Fourier transform. and passing name into. 112. 107–108 fminbnd. 113. 54. 28. 108. 102. 66. 13. 11. 98. 60. 112. 100 Format specifications (in fprintf. 109 Factorial function. 151 ending. 111 Flops (fl oating-point operations). 8. 7. 14 (140). 150 debugging. See Length of a vector discrete sine. 153 example using multiple input and output arguments. 58. 143. 41 ezmesh. 63. 100. 155 comments in.gure) (cont. 55. 23 piecewise. 160 “grouping” together. Finite differences. 159. See Closure fliplr. 14 fill. 108. 46. 101 Field. 100.

54 139 hold. 41 176 . 127–128 Handle. See Identity matrix gcf. 122.4 (66) (120) holding the current plot. 121 object. 159 ifftshift.1 (49). 16 zeroes of. See Graphics See also Polynomials heaviside. 59 definite integrals of. 56. 161 Gravity. 68. 95. 151 Graphical image. 147. 87 Identity matrix. Subsect. 148. 158 ginput. 23. 100. 67 with constant coefficients. 102. 156 ifft. 126 relative error. 156 advanced techniques. 140.2 (58) ode23s. 122. 150 “hijacked”. 67 first-order system. 4. 46. 56. 4 (49) imshow. 82. 137. 122. Subsect. 160 getframe. 127 printing. 161 searching for string. 161 gtext.Functions (mathematical) (cont. 86. 97. Subsect. 16. 114. 161 three-dimensional. 150 Generalized eigenvalue problem. 130. See Conjugate transpose Van der Pol’s equation. 66. 150 import. 65. 57.) Handle graphics. 120 using TEX commands. 86. 66. 32. 152 ode15i. 122. 63. 121 handle for an. 160 Gram-Schmidt algorithm. 155. 138. 65 Imaginary numbers. 92. 101. 139 helpbrowser. 66. 161 two-dimensional. 66. 62. 131. 161 hilb. 50 Bessel’s equation. 111 Help facility. 112. 140 help. 57. 140. 68. 154 customizing lines and markers. Subsect. 63 absolute error. 155 ode23t. 62. 6. Subsect. 66 adaptive step size. 147. 9. 65 imread. Sect. 156 ode113.4 (66) ode15s. 139 I Gaussian elimination. 150 numerical operations on. 138 getting help. 49 ode23tb. 41. 4. 160 global. 150 funm. 156 properties of. Subsect. 66. See Function handle inline.5 (11) Helix. 67. 52 ind2sub. 68. 50 Inf. 126 stiff. 156 if. 130 labelling. 122. 151 common mathematical. 68. 1. 156 imwrite. 58. 9. 32. 54. Sect. 156 Graphics. 67. 20 get. 138. 156 i. 121. 114 hist. 156 See also eye getfield. 17. 157 idst. 65 image. 109. 52 solvers.3 (61). 162 Hermite polynomials. 161 window. 102. Subsect. 49 Initial-value ordinary differential equations. 51. 9. 4.8 (15) local minimum of. 4. 81.5 (68) passing parameters to. 147 multiple plots. 152 ode23. 62. 78. 157 Gauss-Kronrod quadrature (for numerical integration). 143. 74. 4. 128 H . 153 Hilbert matrix. 90. 124 guide. 66 events. 122. 65. 120–127 text properties. 122. 65 imagesc. 122. 156 I. 152 show. 107. 156 extensions. Subsect. 62–66 Duffing’s equation. 161 GUI (Graphical User Interface). 10 handle. 155 Gauss-Lobatto quadrature (for numerical integration). 4. 90 imag. 150 demonstration. 56. 156 changing endpoints. See Interpolation fzero. 33. 65. 156 export. 128 ode45. 147. Histogram. 65. 1. 14. 143. 121 H statistics for. 139. 57. 13. 66. 66. 4. 122. 136 G function file for. 161 properties. 77. 145. 161 multiple windows. 17. 33. 65. 58. 6. 52. 82 gca. 161 saving to a file. 15. 65 importdata.

162 Logical (data type). 47 log1p. 136. 93 Hermite cubic interpolation. See \ Cholesky decomposition. 97 augmented. 9. 150 M Java (programming language). 1. 85 legend. 136 full. 96 interp2. 154 applied to matrices. 94. 15 2.1 (18). 153 defective.5 (11). 159 loglog. 5 (77). 74 diagonals of. Kill current statement. 66. 100. 58. 47 log. 88. 92 cubic splines. 8. 47. 137. 136. 158 J LU decomposition.3 empty. 80. 158 isfinite. Interpolation. 53. 96.2 (96) isa. 29. 13. 94. 137 Logical expression. 53 approximation to. 137. 157 OR (short-circuit) (||). Subsect. 100. 162 islogical. 82.3 (23) solving by \. 96. 94. 159 NOT ( ). 151 Matrix L as column vector. 155 input. See Function. 150 lu. Subsect. 158 isfield. 86 length (number of elements in). 78. 93. 159 ˜ OR (|). 5 (77) Hermitian. 56 int16. 58. 58. See Determinant Life (Conway’s game of). 162 158 interpn. 96. Euclidean length). 16. 109. 114. 10. 137 158 cubic. 159 is not a matrix. 100. 100 K See also Function m-file and Script m-file Machine epsilon (eps). 99. 17.e. 5. 88 j. interp3. 107. 152 int8. 158 linear splines. 17. 151 Integration. 137 Logical operators. 137 Logical functions. 155 isinf. 158 Inner product. 100. 8 Mathematical functions. 5. 38. See Hilbert matrix 177 . Subsect. 61 elementary. 21 solving by linsolve. 151 int64. 155 isnan. 2. 36. 105. 119 Line properties. Sect. 139 logical.Inline functions. 153 Linear system of equations. 117. Subsect. 159 interp1. 62. 152 load. 47 log10. Subsect. 158 inv. 137 result of. 150 keyboard. 97. 100. 160 calculation of. 49. 29. 77–80 lasterr. 94. 24. 2. 159 logm. 162 LOGICAL AND (short circuiting logical operator). 78 Left division. 162 LOGICAL OR (short circuiting logical operator). 22. 96 ischar. 153 Linear splines. 148. 100. 158 isempty. 99. 137. 159. 23 least-squares solution. 48. 136 AND (&). 113 M-files. 158 AND (short-circuit) (&&). 55. 156 condition number. 100. 19 underdetermined. Sect. Subsect. 113. 100. 96. 94. 117 overdetermined. 93. 20. 20 solving by rref. See Interpolation elementary operations. 98. 94. 26 See also norm determinant of. 137. 159 logspace. 55. 82 by submatrices. 9. numerical. See null (below) (82) extracting submatrices. 94. 118. 5. 12. 96. 159 lookfor. 24. 159 EXCLUSIVE OR (xor).7 (34). 30 linspace. 93. 98. 106. 93. 47. 100. Subsect. 13. 151 int32. 158 isequal.3 (82). 90. 16.. 87 Length of a vector (i. 94 Keywords. 158 ipermute. Subsect. 65. 13.3 (82) Hilbert. 57. 14. 22. 78 individual elements. 6. 46. 47 be careful. 101. inline linsolve. 90. 157 result of. 150. 85 Lemniscate of Bernoulli. 105. 94. 159 how to do extrapolation. 36 deleting rows or columns. 88. 94. 78. 136 generating.

154 Null matrix. 122. 137. 90 ode23. 153 pseudoinverse of.9 (37) null. test for. 80. 161 sum of elements. 20 Newton’s laws. 35 Notation (for vectors and matrices). 9. 161 warning of. Subsect. 2. 119 ode113. 157. 157 Overdetermined system. 158 mesh. 131. 161 Vandermonde. See singular value decomposition (above) ode45. 89. 90 QR decomposition. 13. 82. 154 Moore-Penrose pseudoinverse. See ginput pchip. 125. 157 preallocation of. 37. 158 null. 90. 34 orth. 22. 153 unitary. 161 Toeplitz. 154 Mouse location. See Search path pseudoinverse of pause. 76 nargout. 89 positive definite. 122. 57. 128 inverse of. 88 nnz. 158 minimum value. 35 ordinary differential equations Memory (of variables). 9 (117). 122. 88 ode15s. 112. 96. 52. 34 Ordinary differential equations. 35. Sect. 159 Plot. See Linear system of equations Minimum value. 26. See Graphics 178 . 89 manipulation. 25 optimset. 119 num2str. 44. 103. 103. 159 Multidimensional arrays. 9 Moore-Penrose conditions. 122. 37. 155 NaN. 86 ode15i.5 (31) upper triangular part of. 107.9 (37) uses of. generating a. 36. 35 NOT (logical operator). 155 Orthonormal basis. 103. 134. 77. 90. 77. 136. 156 persistent. 157 orderfields. Path. 102 numel. 61. 157 ordinary differential equations and Boundary-value Mean value. 28. See Vandermonde matrix OR (logical operator). 58. 28. 38. 34. 130. 93. 38 pi. 157 Maximum value. 35. 161 specialized. 122. 2. 89 “masking” elements of. 123. 155 identity. 35 ode23tb. 90. 26. 94. 93.Matrix (cont. See Initial-value ordinary differential equations singular. 48 Outer product. 83. 46. 161 SVD. 63. 86. 35 mod. 79. 88 maximum value. See Plotting permute order. 25. 126. 89 O replicating. 2. 112. 34. 98 vector. 61. 2. 159 using set rather than plot. 60. 154 orthogonal. 89 Operator precedence. 37. 162 movie. 101. 112. 88 LU decomposition. 94. 88 Norm unit. 22. 24. 160 ode23s. 90. 75. 122. 88 matrix. 25 odeset. 96. See Line properties nargin. Subsect. See Initial-value mean. See Interpolation N pinv.) ndgrid. 5 multidimensional. 158 max. 84. 26 Ode. 158 methods. 160 Jacobian. 88 Frobenius. 60. 117 ones. 9. 36 Monty Python. 95. 20. 120. 61. 112. 150 line properties. 158 lower triangular part of. 43. 60 Phase plane. 26 reshaping. 50. 42 Parentheses. 88. 150 Piecewise polynomials. 89 meshgrid. 49. 161 tridiagonal. 119. 59. 61. 161 singular value decomposition. 154 movie2avi. 107 generate grid. 154 p -norm.3 (23). 161 sparse. 153 ode23t. 128 norm. Subsect. 89 Null space. Subsect. 89. 156 permute. 42. 8. 158 plot. 112. 53. 140. 122. 155 otherwise. 85. 30 min. 19. 130. 20. See Matrix. 138. 82 path. 151 P Monotonicity. 104. 59. 161 symmetric. 37. 81.

114. 94 randn. roots of. 158 inner. 54. 140. 20. 20 order of. 141 Rational approximation to floating-point number. 95 reshape. 22. 139. 158 Principles about computer arithmetic. definition of. 158 a function. 20 polyvalm. See Dot product =. 13 pol2cart. 90.plot3. 117. Sect. 154 Relational operators. 28. 102. 162 realmin. 154 round-off errors in. 136 normal distribution. 153 Polynomials. 95. generating. 20 roots of. 141 real. 13. 162 rand. 95. 151 spectrum. 81. 9. 23. See Matrix rot90. 162 randi. 158 Power. 158 Printing. 162 uniform distribution. 22. 21. 63 different than in C. 11. See Operator precedence Recursion. 48 roots. 105. 136 pseudorandom numbers. 22. 141. 153 needed less frequently. 29. 23. 8. 136. 158 repmat. 112. 106. 61. 157 >=. 20 evaluating. 135. 139. 161 in polar coordinates. 11 <. 89 a parametric function. 162 Pseudoinverse. 140. 21. 157 while loops. 150 rem. 96 profile. 93. 78 Prime numbers. 135 recommended procedure polyval. 37. 82. See Outer product result of. Subsect. Subsect. 154 for loops. 20. 34. 137. 137. 135. See Matrix rank. 53 quadgk. 160 if statement. 25. 142 Rank of matrix. 53 quad. 20. 83. 139. 153 Positive definite matrix. 46. 26. 26. 161 an implicit function. 155 Quote mark. 28. 136. 54. 96 rng. 54 finding minimum and maximum of. 93. 20. 81. 140. 90. 90 average. 94 Request input. 49. Sect. See Random numbers round. 80 primes. 93. 162 randn. 9. 136. 179 . 111 Predefined variables. 57. 159. 141. 53 QR decomposition. 150 ppval. 162 Random matrix. 93. 93. 13. 20. 58. 56. 33. 155 Q Plotting a curve. 137. 54 R poly. 12 (135). 81. 123 Quadratic polynomial. 153 polyfit. See Display >. 155 Polar coordinates. 158 dot. 83. 20 representing by vector. 153 polyint. 141 realmax. 91 return. 151 Programming language (MATLAB). 21. 14. 8 (91) Remainder. 82.2 (96) outer. 86. 24. 162 state. 24 switch statement. 22. 152 <=. See Inner product ˜ matrix. 154 in each mode. 89. 54. 61. 136. 137. 54 quadl. 158 Product ==. 92 Reverse two variables.3 (9). 20. 7 polar. 141 154 frequency of. 93. 95 rmfield. 9. 137. 141 rats. 158 prod. 154 Pseudorandom numbers. 10 continue loop. 59. 28 break out of. 22. 13.1 (91). 120. 151 flow control. 162 polyder. See Variables Reduced row echelon form. 1. Subsect. 54 randperm. 93. 137. 158 RGB components (of a color). 136 Random numbers. 20. 142 RCOND. 160 differentiating. 135 Gaussian distribution. 135 initial seed. 137. 137. 150 Precedence. 22. 60. 25. 135. 151 Pythagorean theorem. 135. 54. 158 print. 11 Round-off errors. 10. 153 properties. 88 instantaneous. 8. 161 phase plane. 58 qr.

5 (77). 13. 151 switch. 82. 13. 150 str2num. 25. 34. 59 sign. 63. 66. 61. 157 Surface plot. 155 semilogx. 155 sum. 153 spy. 154 sqrt. 109. 58. 52 semilogy. 162 title. 120.Round-o errors (cont. 162 conjugate. 45. 10 rref. 14 sind. 157 tanh. 153 Toeplitz matrix. 152. 68 sprandsym. 14. 36. 118. 43. 61. 119. 154 stairs. 97. 2. 160 Text properties. 128 save. 54. 53. 18. 154 Trigonometric functions. 6 strcmp. 80. 47. 157 saveas. 80. 153. 160 tic. 22. 157 (34) specifications (format). 155. Subsect. 100. 156 spdiags. 119. 155 setfield. 101. 120. 118 Text window. 13. 99 names of. 97. 120. 46. 17. See Character string. 5. 77. 13. 46. 119. 153 tand. 9.2 (81). 148. 158 Save work. See Transpose sinh. 29. 55. 14. 7. 120. 153. 67. 153 squeeze. 120. 37. 16. 20. 88 rerunning previous. 13. See Function m-file sech. 63. 151 Sort numbers. 59 Short circuiting (logical operators). 25. 151 Subfunctions. 111 sec. 154 secd. 160 Title sprandn.) Statements (cont. 96. 139 SVD. 19. 151 subplot. plotting a. 58. 155 warning. See Matrix sprintf. 52. 113 type.7 sscanf. Sect. 49 speye. 55 Stiff ode. 154 Standard deviation. 43. 22. 120. 37. 90. 151 Transpose. See LOGICAL filled-in. 15. 43. 59 AND and LOGICAL OR wire-frame. 31. 156 String. 45 Search path. 28. 137. 153. 155 Splines. 156 surf. 58. 140 Stairstep graph. Subsect. 13. 28. 158 separating on a line. 120. 6 strtrim. See Character string Scientific notation. 13. 55 triu.5 (11). 151 sort. 13. 155 triplequad. 6 strfind. 149 std. 160 TEX. 15 field. 160 text. 105 equal (are two structures). 158 sin z. 62.) 49. 95. 158 Simpson’s method (of numerical integration). 68. 154 spfun. 157 Scope. 157 set. 100. 120. 59. 152. 105 Structure. 147 sparse. 94. 160 for entire figure. See Character string spconvert. See Interpolation multiline. 31. See Singular value decomposition sin. 28. 157 specifications (format). 95. 153 sqrtm. 160 Time. 58. 67. 43. 37. 160 toc. 58. 151 tan. 104. 67 differences from diag. 157 Save terminal commands. 22. 151 sub2ind. 40. 19. 111. 35. 101. multiline sprand. 47 T Singular value decomposition. 122. See cputime and tic and toc spline. 93 executing in text variables. 23. 157. 1. 151 svd. 45. 90 . 119. 13. 151 size. 150 180 . Subsect. 17. 157 Script m-file. 117. 38. 118. 13. 53. 84 toeplitz. 157 S Step function. 45. 25. 13. 35 Taylor series expansion. 35 true. 138 debugging. 84 tril. 51. 58. 156 changing view. 59 shg. 28. 16. 93. 101. 153 Statements TRUE (result of logical expression). See Variables struct. 151 T single. 66. 120.

9. 112. 110 special cases of vectors or matrices. 9. 52. 35 sum of elements. 10. Subsect. 70. 150 i. 35 column vs. testing for. 16 saving local variables in functions. 9 whos. 150 zeros. 1. See Linear system of sort elements. 155 vander. 74. 156 generating. 54. 26 181 . 153 Vandermonde matrix. 8. 7 static. 156 minimum value. 94. 107 scope of. 137. 8. 98 uint32. 7. 20. 20 uint16. 17. 9. 106. 9. 7 Z persistent. 9. 16 loading. Subsect. 136 W varargin. 92 pi. 106. 159 varargout. 10 xor. 9. 58. 6. 35 V vectorize. 59. 94. Subsect. 61. 155 eps. 16. 158 list of. 107 logical. 98 ylabel.1 (18) uint8. 156 repeated elements. 153 ans. 99 X deleting. 7.5 (114) Van der Pol’s equation. 62. 35 equations standard deviation of elements. 9. 6. See Initial-value ordinary profile execution time. 44. 150 overwriting. 74. 108. 74. 100. 9. 155 inputting.2 (7) who. 67. 9 Workspace. 150 NaN. 12 defined. 67. 156 preallocation of. 47 individual elements. 58. 22. 159 while. 150 realmin. 94. 96. 74. 136. 41 Vectorizing code. 108. 35 uiresume. 47 “masking” elements of. 34 uint64. 112. 35 uipanel. 16 Y local. 70. 18 deleting elements. 150 about. 9. 99 uicontrol. 106 valid names. 47 maximum value. 10. U Vector (cont. 150 reverse two. 105 conflict between variable and function name. 106. 102 uiwait. Subsect. 3. 16. 7. 8 Vector average value of elements. 9 global. 67. 107 xlabel. 36 Underdetermined system. 47 mean value of elements. 150 case sensitive. 23. 24 saving. 150 j. 114 differential equations view. 8. 150 zlabel. row. 158 Variables. 20. 59. 62. 93. 8. 95. 9. 155 modifying. 6. 150 Inf. 17.3 (42) See also Character string typeless. 107 overwriting. 61. 107 string. 54. 2. 150 realmax.) equal (are two vectors). 107 predefined.

Index 182 .

- Print SDuploaded byvempadareddy
- Installing and Configuring Simulinkuploaded bySamuel Wagema
- ErrataNMuploaded byMike2322
- Multi-dimensional Matrix Analysis Software MatrixUser v1.0 User Guideuploaded byleoliuf
- The Very Basics of MATLABuploaded byVincent
- kaukicuploaded byFlavia
- 1 an Overview of MATLAB 1uploaded byahmad
- Matlab Basicsuploaded bypitapitul
- 2013 Math 201 a Robbinsuploaded byMehmed Duhovic
- Developing of a Finite Element Program Incorporating Advanced Element Types-Thesisuploaded byConcepción de Puentes
- Arraysuploaded byFaisal Rahman
- JEE Main 2015 Analysis by Resonance Eduventures v1uploaded byNamit Saxena
- books123.me_Numerical.Analysis.Using.MATLAB.pdfuploaded byPablus
- Tutorial 2uploaded bymsohail_kawish
- 7. C Programming - ARRAYuploaded byneo_411
- 10th-Mathsuploaded byVijayaraghavan Purushothaman
- HHT Methoduploaded byMyrwn Oikonomakis
- js_lect2.pdfuploaded byVenkatesh Karri
- Convection Upwinduploaded byfcfcccc
- 1LinearSystems (1)uploaded byEdward Conal
- 10th Maths English-1uploaded byJansy Rani
- Syllabus b R4uploaded byJigar Nayak
- Model Reduction in Chemical Engineeringuploaded byAdilson J. de Assis
- Syllabus buploaded byNelson Ningombam
- Lect Arraysuploaded bysauravnaruka
- VU.BS Course Books Detailsuploaded byUmair Sarwar
- LARSA4D_TrainingManual_BridgeBasicuploaded bypradeepk_136
- Model Rezol. Sist. 3 Ec.uploaded byDaniel Si Simona Chiscareanu
- sorldieidh ihsli hdiow idhs ihe ls hfieuploaded byvonronge
- Matrix Powers-maths Portfoliouploaded bykhanak_angel23

- The.boundary.element.method.with.Programminguploaded byRogerio
- Basic Dynamicsuploaded byRogerio
- Belyaev Strength of Materials Mirpdfuploaded byRogerio
- MATLAB_Handbook.pdfuploaded byRogerio
- numerical.pdfuploaded byRogerio
- Optimización matemática aplicada enunciados, ejercicios y aplica-1.pdfuploaded byRogerio
- SOLIDWORKS 2010 NIVEL III - UNI.pdfuploaded byRogerio
- ⭐Desenvolvimento de programa em linguagem Matlab para cálculo pelo Método de Elementos Finitosuploaded byRogerio
- Matlab Web-Didáticouploaded byRogerio
- simscape_simscape_ug_r2015a (1).pdfuploaded byRogerio
- Matlab Port-Didáticouploaded byRogerio
- Automação Industrial Na Prátricauploaded byRogerio
- Projeto de uma Catapulta em SolidWorksuploaded byRogerio
- 9749364Trazos y Apuntes de Paileria.pdfuploaded byRogerio
- Mountainboard_Design_Project_Student_2010_LR_ENG.pdfuploaded byRogerio
- SolidWorks 2011 - Automaçãouploaded byRogerio
- windmill_tutorial_13b.pdfuploaded byRogerio
- Solidworks Epdm 2015 Datasheetuploaded byRogerio
- windmill_tutorial_13a.pdfuploaded byRogerio
- Solidworks 2016 Solutions Brochureuploaded byRogerio
- Solidworks Simulation 2015 Datasheetuploaded byRogerio
- solucionariodinamica10edicionrusselhibbeler-131219124519-phpapp02.pdfuploaded byRogerio
- fem-exceluploaded byRogerio
- Bridge_Project_WB_2011_ENG.pdfuploaded byRogerio
- Vibrações Mecânicas RAO (4ª Edição) - Exercícios Resolvidos (Todos os capítulos).pdfuploaded byRogerio
- Tutorial SolidWorks 2012.pdfuploaded byRogerio
- docslide.com.br_analise-estrutural.pdfuploaded byRogerio
- 5 - Aula 5 - Detalhamento 2015-1uploaded byRogerio
- suzuki_ms_tcc_guara.pdfuploaded byRogerio

Close Dialog## Are you sure?

This action might not be possible to undo. Are you sure you want to continue?

Loading