# (August 30, 2012

3:16 p.m.)

A MATLAB Tutorial
Ed Overman Department of Mathematics The Ohio State University

Introduction . . . . . . . . . . . . . . . 1 Scalar Calculations . . . . . . . . . . . . . . . . . . . 1.1 Simple Arithmetical Operations 1.2 Variables . . . . . . . . . . . . . . 1.3 Round-oﬀ Errors . . . . . . . . . . . . 1.4 Formatting Printing . . . . . . . . . . . 1.5 Common Mathematical Functions . . . . . . 1.6 Complex Numbers . . . . . . . . . . . 1.7 Script M-ﬁles . . . . . . . . . . . . . 1.8 Help! . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.9 Be Able To Do 2 Arrays: Vector and Matrix Calculations . . . . . 2.1 Generating Matrices . . . . . . . . . . . 2.2 The Colon Operator . . . . . . . . . . . 2.3 Manipulating Matrices . . . . . . . . . . 2.4 Simple Arithmetical Operations . . . . . . . 2.5 Operator Precedence . . . . . . . . . . 2.6 Be Careful! . . . . . . . . . . . . . 2.7 Common Mathematical Functions . . . . . . 2.8 Data Manipulation Commands . . . . . . . 2.9 Advanced Topic: Multidimensional Arrays . . . . . . . . . . . . . . . . 2.10 Be Able To Do 3 Anonymous Functions, Strings, and Other Data Types 3.1 Anonymous Functions . . . . . . . . . . 3.2 Passing Functions as Arguments . . . . . . . 3.3 Strings . . . . . . . . . . . . . . . 3.4 Cell Arrays and Structures . . . . . . . . . 3.5 Advanced Topic: Data Types and Classes . . . . . . . . . . . . . . . . 3.6 Be Able To Do 4 Graphics . . . . . . . . . . . . . . . 4.1 Two-Dimensional Graphics . . . . . . . . . 4.2 Three-Dimensional Graphics . . . . . . . . 4.3 Advanced Topic: Commands . . . . . . . . 4.4 Advanced Topic: Handles and Properties . . . . 4.5 Advanced Topic: GUIs (Graphical User Interfaces) . 4.6 Advanced Topic: Making Movies . . . . . . . 4.7 Be Able To Do . . . . . . . . . . . . 5 Solving Linear Systems of Equations . . . . . . 5.1 Square Linear Systems . . . . . . . . . . 5.2 Catastrophic Round-Oﬀ Errors . . . . . . . 5.3 Overdetermined and Underdetermined Linear Systems 6 File Input-Output . . . . . . . . . . . . . . . . . 7 Some Useful Linear Algebra Functions

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

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

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

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

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

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

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

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

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

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

3 6 6 7 9 10 11 13 14 15 17 17 18 22 23 28 31 32 34 34 37 38 39 40 41 42 43 46 48 49 49 58 61 66 68 74 77 77 78 81 82 83 85

Programming in MATLAB . . . . . . . . 8.1 Flow Control and Logical Variables . . . . . 8.2 Matrix Relational Operators and Logical Operators 8.3 Function M-ﬁles . . . . . . . . . . . 8.4 Odds and Ends . . . . . . . . . . . 8.5 Advanced Topic: Vectorizing Code . . . . . 9 Sparse Matrices . . . . . . . . . . . . 10 Initial-Value Ordinary Diﬀerential Equations . . 10.1 Basic Commands . . . . . . . . . . . 10.2 Advanced Commands . . . . . . . . . 11 Boundary-Value Ordinary Diﬀerential Equations 12 Polynomials and Polynomial Functions . . . . . . . . . 13 Numerical Operations on Functions 14 Discrete Fourier Transform . . . . . . . . 15 Mathematical Functions Applied to Matrices . . Appendix: Reference Tables . . . . . . . . . Arithmetical Operators . . . . . . . . . . Special Characters . . . . . . . . . . . . Getting Help . . . . . . . . . . . . . Predeﬁned Variables . . . . . . . . . . . Format Options . . . . . . . . . . . . . Some Common Mathematical Functions . . . . . Input-Output Functions . . . . . . . . . . Arithmetical Matrix Operations . . . . . . . . Elementary Matrices . . . . . . . . . . . Specialized Matrices . . . . . . . . . . . Elementary Matrix Operations . . . . . . . . Manipulating Matrices . . . . . . . . . . . Odds and Ends . . . . . . . . . . . . . Two-Dimensional Graphics . . . . . . . . . Three-Dimensional Graphics . . . . . . . . . Advanced Graphics Features . . . . . . . . . String Functions, Cell Arrays, Structures, and Classes . Data Manipulation Commands . . . . . . . . Some Useful Functions in Linear Algebra . . . . . Logical and Relational Operators . . . . . . . Flow Control . . . . . . . . . . . . . Logical Functions . . . . . . . . . . . . Programming Language Functions . . . . . . . Debugging Commands . . . . . . . . . . . Discrete Fourier Transform . . . . . . . . . Sparse Matrix Functions . . . . . . . . . . Time Evolution ODE Solvers . . . . . . . . . Boundary-Value Solver . . . . . . . . . . Numerical Operations on Functions . . . . . . . Numerical Operations on Polynomials . . . . . . Matrix Functions . . . . . . . . . . . . Solutions To Exercises . . . . . . . . . . . ASCII Table . . . . . . . . . . . . . . Index . . . . . . . . . . . . . . . . .

8

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

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

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

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

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

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

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

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

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

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

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

91 91 96 100 113 114 117 120 120 125 131 135 138 140 147 149 149 149 150 150 150 151 152 152 153 153 153 154 154 155 155 156 157 157 158 158 158 159 159 160 160 160 161 161 161 162 162 163 167 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 complicated algorithms involving vectors and matrices. • It can numerically solve nonlinear initial-value ordinary diﬀerential equations. • It can numerically solve nonlinear boundary-value ordinary diﬀerential equations. • It contains a wide variety of toolboxes which allow it to perform a wide range of applications from science 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 programming language, but as a powerful calculator that gives you ﬁngertip access to exploring interesting problems 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 diﬃcult 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 operations require the use of sophisticated software packages, which you have to ﬁnd 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 ﬁnd in a reference manual, such as Mastering MATLAB 7 by Duane Hanselman and Bruce Littleﬁeld (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 diﬀerential equations, mathematical modelling, and numerical analysis. It also includes an introduction to two- and three-dimensional graphics because graphics is often the preferred way to present the results of calculations. In this tutorial MATLAB is ﬁrst introduced as a calculator and then as a plotting package. Only afterwards 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 commands 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 ﬁne 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

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

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

1. Scalar Calculations
1.1. Simple Arithmetical Operations

MATLAB can be used as a scientiﬁc 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 12 And 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 scientiﬁc 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 problems. 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 ﬁle, this archive is saved to the ﬁle diary (no extension) in the present directory. If the ﬁle already exists, this is appended to the end of the ﬁle (i.e., the ﬁle is not overwritten). Because of this feature you can use the diary command without fear that crucial work will be overwritten. 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 a-b a*b Addition. Subtraction. Multiplication. a/b a\b a b Division. Left division, (this is exactly the same as b/a ). Exponentiation (i.e., ab ).

ˆ

diary

Saves your input to MATLAB and most of the output to disk. This command toggles diary on and oﬀ. (If no ﬁle is given, it is saved to the ﬁle diary in the current directory.) diary on turns the diary on. diary off turns the diary oﬀ. diary <file name> saves to the named ﬁle. 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 variable 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 example, 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 something completely diﬀerent” in a variable, enter >> str = And now for something completely different (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 deﬁned. Unlike C, for example, variables do not need to be declared (or typed). A variable springs into existence the ﬁrst time it is assigned a value, and its type depends on its context. At start-up time, MATLAB also contains some predeﬁned 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 redeﬁne these predeﬁned variables. For example, if you type > > pi = 2 then you have redeﬁned π — and no error messages will be printed out! Another very useful predeﬁned 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 = Silly Walks 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( And now for something completely different ) >> disp( ------------------------------------------ ) displays -23.6000

ˆ

31.0063 And now for something completely different -----------------------------------------(The command fprintf , which will be discussed in Section 6, allows much ﬁner 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 ﬁrst 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 case catch classdef continue else elseif end for function global if otherwise parfor persistent return spmd switch try 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

If you mean to type
> > > > clear x clear

a great deal of work.

8

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

Warning: eps and realmin are very diﬀerent numbers.1 returns 0 is computer dependent.4. Alternatively. the calculation 1/30000 is displayed in scientiﬁc notation). The optional second argument of “ s ” allows you to enter a string (including spaces) without using quote marks.4. Formatting Printing ˆ However.n The argument to the command input is the string which prompts you for input. 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. for example. 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 ﬁve signiﬁcant digits if scientiﬁc notation is used (e. use the format command in MATLAB. To change how the results are printed out. (On our computer it is 16. For example.1 MATLAB returns 0 rather than 1. For example.) What is not computer dependent is that this leads to errors in numerical calculations. For ex3 ample. on a Mac or a PC use the copy command in the menu. 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.e-40) . s ). 1. and then enter. Use 10 .n MATLAB returns -1. enter >> n = input( n = ). you will see in Section 5. if you want to try some diﬀerent values of n in experimenting with the expression (n1/3 ) − n . and the input is stored in the variable n .) ˆ ˆ ˆ ˆ ˆ Request Input input( <prompt> ) Displays the prompt on the screen and waits for you to input whatever is desired. realmin is approximately the smallest positive number that can be represented on the computer.2 that there are simple examples where this can lead to very incorrect results. which displays a prompt on the screen and waits for you to enter some input from the keyboard. the semicolon keeps the result of this command from being printed out. if you type 1/3 in MATLAB the result is only accurate to approximately this number of digits. ( n (1/3) ) 3 .7764e-15 rather than the correct result of 0. You can easily rerun this line for diﬀerent values of n (as we described above) and explore how round-oﬀ errors can aﬀect simple expressions.1. ( n (1/3) ) 3 . Upper class twit of the year or >> str = input( input string: . Type >> log10(1/eps) and remember the integer part of this number. Note: You can input a character string in two ways: >> str = input( input string: ). This is approximately the maximum number of digits of accuracy of any calculation performed in MATLAB. However. Note: It might not seem important that MATLAB does not do arithmetical operations precisely. whereas eps is approximately the smallest positive number on the computer such that 1 + eps = 1. when we enter >> n = 5. The smallest positive integer n for which >> (1 + 10 (-n)) . and then enter Upper class twit of the year The ﬁrst must enter a string while the second simply enters text until the line ends.g.. You should be able to rerun the last statement executed without having to retype it by using the up-arrow key.e-40 . If you obtain 0. try some diﬀerent values of n . in Unix enter p. when we enter >> (1 + 1.

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

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

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

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

Warning: There is one point we cannot overemphasize. Make sure your . and underscores. Help! Warning: The ﬁle name can consist of (almost any number of) letters (lowercase and/or uppercase).8.1. numbers. i. “ ”.e.

your ﬁle might not execute — MATLAB’s might! Or. you might run a MATLAB function which tries to call a function which has The .le name is not the same as one of MATLAB's commands or functions. If it is.

Displays the actual MATLAB code for a command or function or m-ﬁle. Spaces are not allowed.. you are safe. For example. Comments can appear alone on a line or they can follow a statement that you have entered. not one of yours.) To check this.rst character must be a letter. The on-line help facility in MATLAB is quite extensive. you can enter > > type <file name> before you save your m-ﬁle. “%”. >> help <command> For example. Each line of comments must begin with the percent character.. i. If it cannot ﬁnd this particular function. Help! Before discussing how to obtain help in MATLAB. Lines can also be continued in the MATLAB workspace by using three periods. If you type >> help you will get a list of all the topics that you can peruse further by typing help followed by the name of the topic. If MATLAB returns your m-ﬁle.e. If the ﬁle name doesn’t exist. hold down the control key and type “c”). i. just type >> help format and you will see all the various ways that the output can be formatted. simply type help followed by the name of the command. but it is much more common to use continuation in an m-ﬁle. MATLAB returns ??? Undefined function or variable <file name> .. Odds and Ends edit type .. which returns useful information about a MATLAB function. In this case enter > > doc <file name> (which is discussed in the next section). if you forget the exact form of the format command... A long expression can be continued to a new line by typing three periods followed by the “enter (or 20 “return”) key.. it is often valuable to include comments to explain what you are doing. If your m-ﬁle is very long. Continue an expression onto the next line. This will type out the entire ﬁle 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. 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.e.8. The answer is simply to type C (that is.e. it means you have already saved it. Begin a comment 1. If you want help on a speciﬁc command. i. the same name as yours! (The m-ﬁle it executes depends on the order in which directories are searched for m-ﬁles — see path for more details.8). j =1 1/j can be entered as >> 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9 + 1/10 + 1/11 + 1/12 + . 1/13 + 1/14 + 1/15 + 1/16 + 1/17 + 1/18 + 1/19 + 1/20 although there are much better ways to obtain this same expression with many fewer keystrokes (as you will see in Section 2. % Create a new m-ﬁle or edit an already existing one. Note: Typing ˆ 15 .

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

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

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

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

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

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

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

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

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

suppose that the column vectors { x1 . MATLAB has a command which is useful in changing the shape of a matrix while keeping the same numerical values. For example. 4)T . there is a need to delete elements of a vector or rows or columns of a matrix. in which case this is the same as >> B = A*ones(m. However. 1. We would prefer to simply enter >> Y = X + a (WRONG). This is easily done by using the null matrix [] . This even works if A is a scalar. m. m) is suﬃcient. 1. unfortunately. For example. then B ∈ Rmp×nq . we can enter 26 . One frequent use of repmat is when a speciﬁc operation is to be applied to each row or to each column of a matrix. requires that the new matrix A = repmat(a. n]. xn } have been combined into the matrix X and we want to calculate the corresponding matrix for the vectors yj = xj + a for all j ∈ N[1. n) generates a matrix B which contains m rows and n columns of copies of A . . The statement >> K = reshape(H. as in H(:) . n) reshapes the matrix H ∈ Cp×q into K ∈ Cm×n where m and n must satisfy mn = pq (or an error message will be generated). 6. For example. the second m elements go in the second column. . entering >> x = [1 2 3 4] >> x(2) = [] results in x = (1. occasionally. which.2. Manipulating Matrices rot90(A) rot90 rotates the matrix 90◦ . A column vector is generated from H . (If n = m then repmat(A. x2 . the ﬁrst m elements of this column vector go in the ﬁrst column of K . 5) Occasionally. etc. The command >> B = repmat(A.   24 22 20 30 28 26 Also. the matrix E which has been used throughout this subsection can be easily (and quickly) generated by >> E = reshape([1:30]. That is.3. there is a need to replicate or tile a matrix to form a larger matrix. 3. you can delete the even columns of G by >> G( : . m. 2:2:6 ) = [] The result is   6 4 2  12 10 8    G =  18 16 14  . n). and rot90(A. . As another example. n) (but it is much faster if m and n are large since no multiplication is involved).k) rotates the matrix k ×90◦ . This can be easily done by >> Y = X + repmat(a. n) be created.) If A is a p by q matrix. and the elements of K are taken columnwise from this vector. .

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

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

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

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

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

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

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

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

Since many of them are quite useful in analyzing data. B = (sin aij ). or remove them entirely by using clear . enter >> C = exp(A) Also. 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.e. i] = max(x) If the elements of the vector are all real. if you want C = (eaij ).8.e.nite memory. MATLAB may slow to a crawl and become unusable. this command has no math34 . To calculate the maximum value of the vector x . non-real). For example. Data Manipulation Commands MATLAB has a number of “simple” commands which are used quite frequently. type >> m = max(x) If you also want to know the element of the vector which contains this maximum value... if any of the elements of x are complex (i. For example. i. This is easily done in MATLAB by >> B = sin(A) Similarly. ˆ 2. As we will see in the section on graphics. 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 2.7.e. (1/2) All the common mathematical functions in the table entitled “Some Common Real Mathematical Functions” in Section 1. The whos command will tell you how much memory you are using and show you the size of all your variables. 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. But. you can reduce their sizes by equating them to the null matrix. type >> [m. we have grouped them around this common theme. [] .5 can be used in this way. If you have large matrices which are no longer needed. i.. However.) Here we are interested in how MATLAB applies common mathematical functions to matrices and vectors. the result of this command is the element which has the maximum value. you might want to take the sine of every element of the matrix A = (aij ) ∈ Cm×n . eA and sin A have no meaning unless A is a square matrix. Common Mathematical Functions In linear algebra mathematical functions cannot usually be applied to matrices. even if you have suﬃcient memory. (We will discuss their mathematical deﬁnitions in Section 15. Frequently it is much larger than the amount of physical memory on your computer.

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

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

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

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

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

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

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

if a very simple function is deﬁned by >> r = 10 >> h = @(x) r*x then the function is h(x) = 10x even if r is modiﬁed later. >> 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. Thus. For example.xed when the function is deﬁned. then its value is .

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

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

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

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

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

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

each in the form of a matrix (from a 0×0 matrix up to an n dimensional matrix for any n ). the results of > > a = 5. These logical values are each 1 byte. MATLAB has 15 fundamental classes. which is an instance of the int32 class. Continuing the previous example. In addition. we now list them all. which is an instance of the int8 class. Advanced Topic: Data Types and Classes A is > . For completeness.5 > > i = int32(3) > > j = int8(127) > > ai = a + i > > aj = a + j are ai = 9 . For example. similar to classes in object-oriented programming languages.. MATLAB has user-deﬁned classes. You can also determine if a variable has a particular class by using isa .5 and value 0.e. i.3. to obtain an instance of the single class you can enter A = single(rand(5)) The same technique holds for all the numerical classes. otherwise. Fundamental Classes double single int8 uint8 int16 uint16 int32 uint32 int64 uint64 char logical cell struct function handle double precision ﬂoating-point number (8 bytes) single precision ﬂoating-point number (4 bytes) integer in the range −127 to 128 (1 byte) unsigned integer in the range 0 to 255 (1 byte) integer in the range −215 + 1 to 215 (2 bytes) unsigned integer in the range 0 to 216 − 1 (2 bytes) integer in the range −231 + 1 to 231 (4 bytes) unsigned integer in the range 0 to 232 − 1 (4 bytes) integer in the range −263 + 1 to 263 (8 bytes) unsigned integer in the range 0 to 264 − 1 (8 bytes) string (each character is 2 bytes) logical (true or false) (1 byte) its elements can be instances of any classes and sizes its ﬁelds can be instances of any classes and sizes allows indirect references to functions For example.5. A simple template for generating a new class is 47 . use the function class . false. int8 ) returns 0 . and aj = 127 . >> class(i) returns int32 and >> isa(i. Warning: Caveat Emptor! The procedures for combining diﬀerent numerical classes is very diﬀerent from other programming languages. To determine the class of a variable.

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

Two-Dimensional Graphics Evaluate the function in the cell element (2. Two-Dimensional Graphics The MATLAB function plot is used to constructing basic two-dimensional plots. y1) >> plot(x. >> xx = linspace(0.1.4. 2) at x = 5. generate n data points on the curve by >> n = 100. We plot these data points by >> plot(x. 2 . n). All graphical images are generated in a “graphics window”. and its ﬁrst ˆ 49 . Note: Most MATLAB commands which take vectors as arguments will accept either row or column vectors. 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 ﬁne control over the appearance of the plots. >> x = 2*pi*[0:n-1] /(n-1). We can generate the x coordinates of the data points more easily by >> x = linspace(0. For example. you want to plot y3 = sin cos(x2 − x) for x ∈ [0. <last point>. this demo makes it quite easy to generate your own graphics. x3 (b) f (x) = x1 − ex2 + cos . Hint: Use the heaviside function. these images can be output from MATLAB and printed on a wide variety of output devices. including color ink-jet printers and black-and-white and color laser printers. 3. Graphics A very useful feature of MATLAB is its ability to generate high quality two. 2*pi. <number of points>) so it is much harder to make a mistake. y ) = sin(x + y ) cos(x − y ). 4. 4. 2π ]. >> xx = 8*[0:n-1]/(n-1). more advanced graphics commands are discussed in the next section.and three-dimensional plots using simple and ﬂexible commands. y2) >> plot(xx. n). 2π ] 0 otherwise. and (2) round-oﬀ errors are minimalized so you are guaranteed that x has exactly n elements.1. y3) Note that the axes are changed for every plot so that the curve just ﬁts inside the axes. 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>. >> y3 = sin( cos( xx.xx ) ). 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. which is completely separate from the “text window” in which MATLAB commands are typed. non-graphical and graphical commands can be completely intermixed. |x1 + x2 | + 1 (c) f (x) = 1 − cos x for x ∈ [0. Use anonymous functions to deﬁne (a) f (x. In addition. Thus. We begin by considering only the basic commands. >> y1 = sin(x). First. also. 8. >> y2 = exp(cos(x)). suppose you want to plot the functions y1 = sin x and y2 = ecos x for x ∈ [0.

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

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

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

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

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

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

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

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

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

1001).*Y ). These contour lines are labelled by >> [C. Y. y . i. That is. x2 .. i. 2. y2 . 90◦ is the x axis. v) where v is a vector of the values. You can change the view of a three-dimensional plot by clicking on the menu item which shows a counterclockwise rotation. y) in three-dimensions with the hidden surfaces removed.. Y] = meshgrid(x. the underlying mesh must be created. and z have been deﬁned using anonymous functions. . >> F = (X + Y). >> s = sin(t). . . The easiest way is to use the command meshgrid . { y1 . Then put the mouse in the plot. you can give the angles from the origin of the plot to your eye by view(<azimuth>. If you type >> contour(X. yn } . . You can also change it by using the view command.). etc. h) Also. .2. We discuss how to change the colors. you can put a label on the z -axis by >> zlabel(<string>) There is also an “easy” plot3 command. z (t) for t ∈ (0. you can give the coordinates of a vector pointing from the origin of the plot to your eye by view([x y z]) . and even how to use the colors as another variable. The function f can then be evaluated at these mesh nodes. F) generates a colored.2*Y. and the y axis. you will be looking down the z axis at curves which represent lines of constant elevation (i. y (t). F) >> clabel(C. Y. Y. . n in the x–y plane. 180◦ is the y axis. F) you will see contour plots of the surface.*s. >> x = linspace(-3. { x1 . Y. Y. ﬁlled-in surface. 2. • Second. For example. You can again change your view of these curves by using the view command. To obtain a ﬁlled contour plot enter >> contourf(X. It generates the curve x(t). MATLAB also plots surfaces z = f(x. . First. .e.*c.) 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.. and begin moving it. >> plot3(t. Three-Dimensional Graphics enter >> t = linspace(0. . y). xm } . 41) . F) generates a colored. constant z values). F) you will see contour plots of the surface in three dimensions. yj ) i = 1. . which can be called in either of two ways: • First. . h] = contour(X.*exp( -X. you change the domain of t by specifying the additional argument [tmin. t) and to generate a conical helix enter >> t = linspace(0. into the rectangular mesh (xi . >> s = sin(t). 2001). Y. 20*pi. 3. contour lines are plotted at speciﬁc values by >> contour(X. >> c = cos(t). y. wire-frame surface whereas >> surf(X. m . F) If you do not want to bother with generating the mesh explicitly. 90◦ is on the +z axis. Again. . where you enter the coordinates of the vector. j = 1.4.e. F. . . >> y = linspace(-2. in the next section. This combines a discretization of the x axis. . 20*pi. Y.e. etc. >> c = cos(t). 2π ) by >> ezplot3(x. s. . hold down the left button. t. you can generate “easy” plots by 59 . z) if x .*X . >> plot3(c. >> mesh(X. 61) . t) Also. >> [X. tmax] . 2. <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. If we type >> contour3(X.

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θ 1.2 − r cos 3θ for r ≤ 1

f (r, θ) = 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 understood 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) ; >> y = linspace(-2, 2, 41) ; >> z = linspace(0, 1, 11) ; >> [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 diﬀerence between the two functions is that the order of the ﬁrst 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 X = 2 3

1 2 3

1 2 3

  1 4 2 , Y = 4 3 4

5 5 5

6 6 6

 7 7 7

60

Three-Dimensional Graphics plot3(x, y, z) Plots the data points in Cartesian coordinates. The general form of this command is plot(x1, y1, z1, s1, x2, y2, z2, s2, ...) where s1 , s2 , . . . are optional character strings containing information about the type of line, mark, and color to be used. Generates an “easy” plot in 3-D. Plots a 3-D surface using a wire mesh. Generates an “easy” 3-D surface using a wire mesh. Plots a 3-D ﬁlled-in surface. Generates an “easy” 3-D ﬁlled-in surface. Changes the viewpoint of a 3-D surface plot by view(<azimuth>, <elevation>) or view([x y z]) . Generates a 2-D grid given the x-coordinates and the y -coordinates of the mesh lines. Same as meshgrid except that the two arguments are reversed. convert polar to cartesian coordinates. Puts a label on the z -axis. Controls the scaling and the appearance of the axes. axis([xmin xmax ymin ymax zmin zmax]) changes the endpoints of the axes. Plots a contour looking down the z axis. Plots a ﬁlled contour. Generates an “easy” contour looking down the z axis. Plots a contour in 3-D. Generates an “easy” contour in 3-D. Label contour lines generated by contour or contour3. Remember than subplot can also be called in 3-D to put a number of plots in one graphics window.

ezplot3(<fnc 1>, <fnc 2>, <fnc 3>) mesh(X, Y, Z) ezmesh(<2D fnc>) surf(X, Y, Z) ezsurf(<2D fnc>) view meshgrid(x, y) ndgrid(x, y) pol2cart(Th, R) zlabel(<string>) axis

contour(X, Y, Z) contourf(X, Y, Z) ezcontour(<2D fnc>) contour3(X, Y, Z) ezcontour3(<2D fnc>) clabel subplot(m, n, p)

4.3.

In the previous subsections we have discussed how to use “simple” graphics commands to generate basic plots. MATLAB can also do much more “interesting” graphics, and even publication quality graphics. Here we discuss some of the more useful advanced features. We divide the topic into two subsections: the ﬁrst discusses the commands themselves and the second discusses how to change some of the properties of these commands. Note: The demonstration program shows many more of the graphics capabilities of MATLAB. Enter demo and then in Help Navigator click on Graphics. First, however, we want to return to the plot command. We have already discussed plot(x, y) and plot(x, y, LineSpec) where LineSpec contains one or more symbols which customize the line. Additionally, you can use >> plot(x, y, PropertyName , PropertyValue, ...) or >> plot(x, y, LineSpec, PropertyName , PropertyValue, ...) where ... indicates that there can be more property names and values. There are a huge number of properties which can be used. The three names and values we discuss refer to the color of the line, its width, and the size of any markers. • Color , ’?’ – where ? is a single character denoting one of the colors in the table. Color , ’?...?’ – where ?...? is the long name of one of the colors. Color , [r, g, b] – where this denotes the color by giving its red, green, and blue intensities in the 61

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

ˆ

ˆ ˆ

ˆ

ˆ

On a Macintosh computer you probably do not have a center mouse button.

62

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

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

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

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

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

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

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

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

4.5. Advanced Topic: GUIs (Graphical User Interfaces) 71 .

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

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

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

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

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

The solutions are given on page 163. force the axes to be to the same scale. explain how the sum of all the modes is calculated in the function g. 2. Add a frame to the avi ﬁle. aj 1 x1 + aj 2 x2 + · · · + ajn xn = bj . Solving Linear Systems of Equations Movies avifile addframe getframe close (<avifile>) movie movie2avi saveas Create a new avi ﬁle. contains ex − p3 (x). (b) Then plot p 3 ( x) = 1 + x2 x3 x + + 1! 2! 3! on the same graph. (e) The above plot is not very instructive because ex − p3 (x) is much smaller than either ex or p3 (x). 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 . (a) Begin by plotting ex for x ∈ [−1. ex − p3 (x) on the same graph. Put labels on the x and y axes and a silly title on the entire plot. generate a new graph containing all three curves by using only one plot command. . use two plots. . . . +1].5. 3. y ∈ [−2. These two plots should ﬁll an entire sheet of paper. and let all three curves have diﬀerent colors. The ﬁrst plot contains ex and p3 (x) and the second plot. . Note: There are an inﬁnite number of answers to this part. Close the ﬁle opened with avifile . (a) Plot this function for x. Note: Make sure you use the “ . 1. Explain how the local function running gaussians works. Plot ex and one of its Taylor series approximations. In particular. 77 . y ) = (x2 + 4y 2 ) sin(2πx) sin(2πy ) . am1 x1 + am2 x2 + · · · + amn xn = bm . . (c) Also plot the diﬀerence between ex and this cubic polynomial. 4. What does the surface look like if you don’t? (b) This surface has high peaks which interfere with your view of the surface. 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. . Save a ﬁgure to disk. Instead. 5. i. which is immediately below the ﬁrst. . (d) Next. Get the current frame. . Be Able To Do After reading this section you should be able to do the following exercises. Save the current movie frames to an avi ﬁle.. . Play movie frames.7.∗ ” operator in front of each sine term. +2].e. Consider the function f (x.

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

3 6 9  −1 −1  . Of course. For example. which is equivalent to the matrix equation  1 A = 4 7 Ax = b where    2 3 −1 5 6  and b =  −1  . 8 10 0 The augmented matrix for this linear system is x1 1  4 7  x2 2 5 8 x3 3 6 10 = rhs  −1 −1  .5. consider the system of equations x 1 + 2 x 2 + 3 x 3 = −1 4 x 1 + 5 x 2 + 6 x 3 = −1 7x1 + 8x2 + 10x3 = 0 . 7 8 9 −1 Since A is a singular matrix. but only on linear systems of equations. the linear system has The augmented matrix for this linear system is  1 2 4 5 7 8 Entering >> rref([A b]) returns the augmented matrix  1 0 0 1 0 0 −1 2 0 79  1 −1  . is particularly easy to solve. The result is an augmented matrix which. you could just as easily have found the solution by >> x = A\b so let us now consider the slightly diﬀerent linear system x1 + 2x2 + 3x3 = −1 4x1 + 5x2 + 6x3 = −1 7x1 + 6x2 + 9x3 = −1 . This is equivalent to the matrix equation Ax = b where     1 2 3 −1 A =  4 5 6  and b =  −1  . x2 = −3.1. when written back out as a linear system of equations. and x3 = 1. 0 (We have included the header information for the last time. 0 . Square Linear Systems rref operates on this augmented matrix to make as many of the elements as possible zero by using allowed operations on linear equations — these operations are not allowed on matrices. 0 0 1 1 Clearly. 0 either no solutions or an inﬁnite number of solutions.) Entering >> rref([A b]) returns the augmented matrix   1 0 0 2 0 1 0 −3  . the solution of the linear system is x1 = 2.

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

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

ve signiﬁcant digits! (To see how 81 .

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

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

Each conversion character is preceded by “%”. it is a little more diﬃcult to print it to a ﬁle. To brieﬂy review some of the C format speciﬁcations.. and the two integers are separated by a period. fprintf can also be used to format data on the screen by omitting the fid at the beginning of the argument list.. <format string>. The format string is very similar to that of C. If it is [m n] . to integer notation. x) and the results are r w x = -23. and. If necessary. s The argument is a string. is optional. it is possible to display a variable using as little or as much control as desired. Thus. the ﬁle is created. the conversion characters are: d The argument is converted to decimal notation. g The argument is a ﬂoating-point number in either “E” or decimal notation. Str(i. • If the maximum ﬁeld width is larger than the minimum ﬁeld width. <variable 1>. if x contains −23. For example. a append to the end of the ﬁle (everything previously contained in the ﬁle is retained). These variables are printed out in order and matrices are converted to column vectors (i.6 three diﬀerent ways to display it are >> x >> disp([ x = .:)). 1)] fprintf(fid. If the fopen command fails.. . e The argument is a ﬂoating-point number in “E” format. or is not used at all. r+ read from and write to the ﬁle (anything previously contained in the ﬁle is overwritten). the output appears on the screen. However.6.6000 -2. the ﬁle is created. c The argument is a single character. >> Str=num2str(A). enter >> A = fscanf(fid. the minimum ﬁeld width is preceded by an integer which speciﬁes the maximum ﬁeld width. <format string>. The following works and can be entered on one line. To write formatted data to a ﬁle. −1 is returned in the ﬁle identiﬁer. <size>) The data is read from the ﬁle speciﬁed in a previous fopen command according to the format string and put into the matrix A . Enter >> fclose(fid) if a ﬁle needs to be closed. w+ read from and write to the ﬁle (anything previously contained in the ﬁle is overwritten).6000 x = -23.6e\n .end To read formatted data from a ﬁle. If fid is omitted. If necessary. num2str(x)]) >> fprintf( %12. enter >> fprintf(fid. write only to the ﬁle (anything previously contained in the ﬁle is overwritten). then A is a matrix of this size. if possible. %s\n .for i = [1:size(Str. f The argument is a ﬂoating-point number in decimal notation. <variable 2>. If it is a scalar. A is actually a vector. File Input-Output read only from the ﬁle. The size argument. 84 . with the exception that the format string is cycled through until the end of the ﬁle is reached or the number of elements speciﬁed by size is attained. A → A(:) ).360000e+01 Note: It is easy to print the matrix A in the MATLAB workspace as we just described.) The elements contained in the variables are written to the ﬁle speciﬁed in a previous fopen command according to the format string. The following may appear between the “%” and the conversion character: • A minus sign which speciﬁes left adjustment rather than right adjustment. although it is actually a number of statements. • An integer which speciﬁes a minimum ﬁeld width.e. which puts an upper limit on the amount of data to be read.

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

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

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

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

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

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

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

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

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

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

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

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

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

5). The diﬀerence between c and iv is that c is a logical vector and iv is a scalar vector. Matrix Relational Operators and Logical Operators does not require any multiplication is >> ijF = find(F <= 0. whereas D is a matrix of ones and zeroes which explicitly shows which elements should be zeroed.8. 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. otherwise 0 is returned. 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.) This requires some explanation. 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”. we can check 98 . >> F(ijF) = -pi or even >> F( find(F <= 0. >> c = (v >= .75 1. The command >> any(x) returns 1 if any element of the vector x is nonzero (i.0] .5 . it operates on each column and returns a row vector. When applied to a matrix.5). Enter >> v = [0:. For example. 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”. so that v = [0 . To explain logical arrays more clearly.25:1].75 1. Another.2.5).e.0] and c = [0 0 1 1 1] where “0” denotes false and “1” denotes true. 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. for every element of D which is zero. we take a speciﬁc and very simple example. the corresponding element of F is replaced by −π .5) rather than the vector ijF . On the other hand >> iv = find(v < . MATLAB also has two functions that test vectors and matrices for logical conditions. nothing is done.25 . The result of >> v(c) is [. and only logical matrices and vectors can be used as “masks”. “TRUE”).5 . Recall that ijF is a vector which contains the actual locations of the elements we want to zero out.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.0] . c is a logical vector and v(c) deletes the elements of v which are “false”.5 . 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 deﬁned using a logical operator. That is. slightly diﬀerent method uses the matrix >> D = (F <= 0.. returns v = [. To see that D is a logical variable and F is not. enter >> F(2*D) We can also convert a non-logical variable to a logical one by using the MATLAB command logical .75 1. returns iv = [1 2] and >> v(iv) = [].5) = -pi to combine everything into a single statement.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

What is the average length of these intervals and what is their standard deviation? Also.8. only include intervals which lie completely within y (i. consider the intervals in y where yi > R . It is not diﬃcult to write such a code using ﬂow control statements: 115 . now hilb local they are “roughly” comparable — depending on the computer and operating system. H = E. % J is a row vector J = J(ones(n. However. As a realistic example of method (2). Advanced Topic: Vectorizing Code Continuing with this example. currently the MATLAB function hilb is written as function H = hilb2(n) J = 1:n. In particular. suppose you have a large vector y which is the discretization of a smooth function and you want to know some information about it. it is frequently not necessary to convert simple loops into complicated vector code. % J is now an n by n matrix with each row being 1:n I = J .e./(I+J-1). as can be seen by entering >> edit hilb In the past this code ran nearly 20 times as fast as hilb local . The reason is that MATLAB has greatly improved its handling of for and while statements.. Thus.5. % I is an n by n matrix with each column being 1:n E = ones(n.:). 1). n). ignore any intervals which begin or end y ).

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

For example. Thus. We could preallocate them to a large size. which is generally a full matrix. For example. and then strip out the unused elements at the end of the code. This is very useful for improving the performance of a code by determining where most of the CPU time is spent. MATLAB is completely responsible for handling all the details of their use: there are no special commands needed to work with sparse matrices. we have no way to preallocate these vectors to a “reasonable” size. Finally. s. while for sparse matrices (i.e. 2 −2n + 2 1        0 117 . . most of the elements are nonzero) MATLAB stores all the elements. You have two alternatives: ﬁrst.e. m. Sparse Matrices function ylen intvl = get intervals fast(y. ). The second is to enter all the nonzero elements of S ∈ Cm×n individually by >> S = sparse(i. instead. their row numbers and column numbers) and their values. then the maximum number of nonzero elements is 3n−2. The ﬁrst is to use speye to create a sparse identity matrix instead of using eye which creates a full identity matrix. second. there are a number of commands which are inappropriate for sparse matrices. Sparse Matrices Many matrices that arise in applications only have a small proportion of nonzero elements. you can use condest which estimates the condition number by using Gaussian elimination. % (4) if y(1) > R % (5). 9. . However. say length(y)/4 . Once sparse matrices are generated. There are three common commands in MATLAB for creating sparse matrices. most of the elements are zero) MATLAB only stores the nonzero elements: their locations (i.. and MATLAB generally generates a warning message and refers you to more appropriate commands. check if we begin in an interval ylen(1) = []. Since we have no idea how many intervals there are. . the square bidiagonal matrix     S=   n −2 n−1 −4 n−2 −6 . if n is “large” (which commonly means in the hundreds or thousands or .. Note: In get intervals slow we did not preallocate the vectors yin and yout . % (2) ye = find(yd). sparse matrices require much less storage space in the computer. or. In addition. However. 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. cond(S) has to calculate S−1 . if T ∈ Cn×n is a tridiagonal matrix. . use full to generate a full matrix and use the desired command. j. For full matrices (i. 0 .. This is certainly a small proportion of the total number of elements. % yes end % get every other length ylen intvl = ylen( 1:2:length(ylen) ). R) yr = (y > R). the computation time for matrix operations is signiﬁcantly reduced because zero elements can be ignored. i. n2 . % (3) ylen = diff(ye). the question remains: is the time savings signiﬁcant? For “large” y the CPU time is reduced by over 20 (but this can vary greatly depending on y and R ). For example.e. % (1) yd = diff(yr)...e. unless the number of intervals is in the tens of thousands.. Improving Eﬃciency of Function profile Proﬁle the execution time of a MATLAB code. this will probably not save any time.9. use the recommended alternative command.

. if d = (0. [1:n]. .) Thus.2 is 0. [n:-1:1]. B is a min{ m. it is diﬃcult to be sure that S is precisely what is desired.. For example. 5) 118 . The above command is easier to understand. m. n) + .. -1) + diag([6:8]. 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 > > > > or by > > > > generated as a sparse matrix by A = diag([1:4]. which does not appear in S . Sparse Matrices has the following nonzero elements i 1 2 3 . even if it does require adding two sparse matrices. n−1 n si. d.j n n−1 n−2 . The diﬃculty 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 . [2:n]. . n) which is short for >> SZ = sparse([]. 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. a zero m×n matrix can be generated by >> SZ = sparse(m. . n. 2 1 i 1 2 3 . []. m. []. In addition. n }×p matrix and its columns become the diagonals of S speciﬁed by d ∈ Cp . . n) Warning: Be Careful! The command spdiags is somewhat similar to diag but must be handled more carefully. n) The third common command for generating sparse matrices is >> S = spdiags(B. n. −2n + 4 −2n + 2 A simple way to generate this matrix is by entering >> S = sparse([1:n]. sparse([1:n-1]. Note that the element b1. . n) We could. 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. .j −2 −4 −6 . n−1 n si. 2) S1 = sparse(A) B = [ [1:4] 0. 5. [-2:-2:-2*n+2]. n) which works with entire diagonals of S . . of course. 0 0 [6:8] ] S1 = spdiags(B. . n. [-1 2]. The padding is done so that all the elements in the k th row of B come from the k th column of S . . but it would be more complicated. Since the output from this command is basically just the above table. 1)T then the ﬁrst 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. (For example. n−2 n−1 j 2 3 4 . n−1 n j 1 2 3 . . [0 1] .9. we can also generate the matrix S given above by >> B = [ [n:-1:1] [0:-2:-2*n+2] ] >> S = spdiags(B. generate S using one sparse command. .

9. Sparse Matrices

In the latter case note that the columns of B have to be padded with zeroes so that each column has ﬁve elements, whereas in the former case the vector which becomes the particular diagonal precisely ﬁts into the diagonal. The element s1,3 of S1 contains the value 6. It appears 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 speciﬁed by d . Thus, a third way to generate the matrix S given above is >> S = spdiags([n:-1:1] , [0], n, n) >> S = spdiags([0:-2:-2*n+2] , [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 structure 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 matrices by sprandn . There are a number of diﬀerent 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 matrix will also be positive deﬁnite. (There is no equivalent command for non-sparse matrices so use full(sprandsym(...)) Additionally, sparse matrices can be input from a data ﬁle with the spconvert command. Use csvread or load to input the sparsity pattern from a data ﬁle into the matrix <sparsity matrix> . This data ﬁle should contain three columns: the ﬁrst 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 ﬁle 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

10.1. Basic Commands

Sparse Matrix Functions speye sprand sprandn sparse spdiags full find nnz spfun( <function name> , A) spy spconvert sprandsym Generates a sparse identity matrix. The arguments are the same as for eye . Sparse uniformly distributed random symmetric matrix; the matrix can also be positive deﬁnite. Sparse normally distributed random matrix. Generates a sparse matrix elementwise. Generates a sparse matrix by diagonals or extracts some diagonals of a sparse matrix. Converts a sparse matrix to a full matrix. Finds the indices of the nonzero elements of a matrix. Returns the number of nonzero elements in a matrix. Applies the function to the nonzero elements of A . Plots the locations of the nonzero elements of a matrix. Generates a sparse matrix given the nonzero elements and their indices. Generates a sparse uniformly distributed symmetric random matrix; the matrix can also be positive deﬁnite.

10. Initial-Value Ordinary Diﬀerential Equations
Most initial-value ordinary diﬀerential equations cannot be solved analytically. Instead, using MATLAB we can obtain a numerical approximation to the ode system d y = f(t, y) dt for t ≥ t0

where y ∈ Rn with initial condition y(t0 ) = y0 . The basic MATLAB commands are easily learned. However, the commands become more involved if we want to explore the trajectories in more detail. Thus, 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. We also provide a large number of examples, many more than in other sections of this overview, to provide a template of how to actually use the advanced features.

10.1.

Basic Commands

In this subsection we focus on the particular example y + αy − y (1 − βy 2 ) = Γ cos ωt , which is called Duﬃng’s equation. This ode has many diﬀerent types of behavior depending on the values of the parameters α, β , Γ, and ω . As written, this is not in the form of a ﬁrst-order system. To transform it we deﬁne y1 = y and y2 = y1 = y so that y1 = y2
2 y2 = y1 = y = y1 (1 − βy1 ) − αy2 + Γ cos ωt

or y1 y2 = y2 2 y1 (1 − βy1 ) − αy2 + Γ cos ωt 120 .

10.1. Basic Commands

Note: This same “trick” can be applied to an nth order by deﬁning y1 = y , y2 = y1 , y3 = y2 , . . . , yn = yn−1 . Before discussing how to solve Duﬃng’s equation speciﬁcally, we discuss the commands which solve time-evolution odes. To obtain a numerical solution to a time-evolution ﬁrst-order ode system, enter >> <ode solver>(<function handle>, tspan, y0) or >> [t, Y] = <ode solver>(<function handle>, tspan, y0) or >> sol = <ode solver>(<function handle>, tspan, y0) First, we have to choose which ode solver to use; this is discussed in detail shortly. It would be possible for MATLAB itself to decide which numerical method to employ. However, there are good reasons why the decision should be left in the hand of the user. Warning: Make sure you understand how to enter the name of the function handle. This is discussed at length in Section 3.2, and we also brieﬂy discuss it below. All of the solvers use the same input and output arguments, which we now discuss. The input parameters are: function The name of the function handle that calculates f(t, y). tspan The vector that speciﬁes the time interval over which the solution is to be calculated. If this vector contains two elements, these are the initial time and the ﬁnal time; in this case the ode solver determines the times at which the solution is output. If this vector contains more than two elements, these are the only times at which the solution is output. Note: the ﬁnal time can be less than the initial time, in which case the trajectory is moving backwards in time. y0 The vector of the initial conditions for the ode. If there are no output parameters, the individual elements of the solution, i.e., y1 (t), y2 (t), . . . , yn (t), are plotted vs. t on a single plot. The circles on the trajectories show the actual times at which the solution is calculated. If there are two output parameters, these are: t The column vector of the times at which the solution is calculated.† Y The matrix which contains the numerical solution at the times corresponding to t . The ﬁrst column of Y contains y1 , the second column y2 , etc.‡ If there is one output parameter, then it is a structure. The output is now sol.x The column vector of the times at which the solution is calculated. sol.y The matrix which contains the numerical solution at the times corresponding to t . There are seven distinct ode solvers which can be used, as shown in the table below. All these ode solvers use an adaptive step size to control the error in the numerical solution. Each time step is chosen to try to keep the local error within the prescribed bounds as determined by the relative error and the absolute error tolerances (although it does not always succeed). That is, ei , which is the error in yi , is supposed to satisfy ei ≤ max{ RelTol · |yi |, AbsTol(i) } where the default value of RelTol is 10−3 and of the vector AbsTol is 10−6 for each element. (However, there is no guarantee that the error in the numerical calculation actually satisﬁes this bound.)

† ‡

The t in [t, Y] is unrelated to the t argument in the function duffing .

We have capitalized the Y in [t, Y] to indicate that the output is a matrix whereas the argument y is a vector in the function.

121

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

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

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

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

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

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

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

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

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

y) dx 131 for x ∈ [a. y. we not only have to input the initial condition y(0) = (0. We can solve Bessel’s equation for t ∈ [0. y.11. we will concentrate on n = 1. Y(:. y ) = 0 . When we convert Bessel’s equation to the ﬁrst order system we again let y1 (t) = y (t) and y2 (t) = y (t) and leave the t2 in the numerator to obtain y1 t2 y2 = y2 −ty2 − (t2 − 1)y1 Previously.2) for t ≥ 1 with the initial conditions that y (1) and y (1) are given. tspan = [0 10] y0 = [0. y2 (0) . 11. If we write Bessel’s equation as 1 n2 y (t) + y (t) + 1 − 2 t t y (t) = 0 (10. The ode solvers we discussed previously can handle (10.0] [t. 1)T . b] . Boundary-value odes are also odes of the form d y = f(x.2). y ) = y1 − y2 t2 y2 + ty2 + (t2 − 1)y1 . yp) [yp(1)-y(2). y. y ) = 0 so that g(t.1) is preferred to (10. Boundary-Value Ordinary Diﬀerential Equations Jn (t) and. At t = 0 the ode reduces to −y (0) = 0 and so we require y (0) = 0. y0. 10] by g = @(t. It is easy to calculate y1 (0) = y2 (0).1) with respect to t to obtain t2 y (t) + 3ty (t) + t2 y (t) + 2ty (t) = 0 and diﬀerentiate it again to obtain t2 y Now set >> >> >> >> >> >> (t) + 5ty (t) + (t2 + 3)y (t) + 4ty (t) + 2y (t) = 0 . we write it as g(t. Diﬀerentiate (10. but we also have to input T y (0) = y1 (0).2) we clearly have a problem at t = 0 and for t ≈ 0. The free initial condition is y (0) and for this example we choose y (0) = 1. but this form has a problem when t = 0. Instead. y. y ).t 2 *yp(2)+t*y(2)+(t 2 -1)*y(1)]. for speciﬁcity. we have always written the ﬁrst-order system as y = f(t.1] yp0 = [1.Y] = ode15i(g. t = 0 to obtain y (0) = 0. Finally. a completely diﬀerent method of solution is required for t ≥ 0 and the form (10. but y2 (0) ≡ y (0) is more complicated. Boundary-Value Ordinary Diﬀerential Equations In addition to initial-value ordinary diﬀerential equations there is a second type of odes that MATLAB can solve numerically. tspan.1)) ˆ ˆ Implicit ODE Solver ode15i Stiﬀ ode solver for the fully implicit ode f(t. yp0) plot(t. However.

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

>> Ypt = deval(sol. @nlode y ic). >> sol = bvp4c(@nlode.x). For example. and plot. @nlode bc.*(1 . This is often unacceptable because constant initial guesses may be so far from the solution that convergence cannot be obtained. specify the structure solinit directly by entering >> x = linspace(0. >> y1 val = ???. [y1. Boundary-Value Ordinary Diﬀerential Equations or >> bvpinit(x. 21). 1.2*x). <initial guess function>) For example. >> y2 = 4*A*(1 .y2]. 4*A*(1-2*x)]. Ypt(1. it works for now. if we want the initial iterate to be a parabola which is zero at x = 0 and 1 and has maximum value A then y (x) = y1 (x) = 4Ax(1 − x) and y (x) = y2 (x) = 4A(1 − 2x) then we can write >> x = linspace(0. where nrode y ic is written as function y ic = nlode y ic(x) global A y ic = [4*A*x. >> y1 = 4*A*x. xpt. 21).x). Instead. If you really. the numerical solution y by %%%%% script m-file: nlode2 > > xpt = linspace(0.y = [y1. >> solinit = bvpinit(x. 1. 133 . However. r ) Having done all this work. >> solinit. where y1 val and y2 val are scalar values. 21). if xi = (i − 1)∆x where x1 = 0 and xn = 1 then we determine. >> solinit. 101). solinit).2*x). 21). >> y2 = 4*A*(1 . >> y1 = 4*A*x. The only alternative is to write >> x = linspace(0. Warning: This is dangerous because future versions of Matlab might change the ﬁeldnames of the structure solinit. y2 val]). xpt).:). >> y2 val = ???. What we would like to do is >> x = linspace(0. 21). we now combine everything into the function m-ﬁle nlode all to show how much easier it is to use nested functions and to combine everything into one primary function. @nlode y ic). >> solinit = bvpinit(x. [y1 val. really need y1 and y2 to be vectors. % WRONG This fails because y1 and y2 must be scalar variables and not vectors. 1. >> solinit = bvpinit(x.11. 1. >> plot(xpt. Thus the initial guess is y1 = y1 val*ones(size(x)) and y2 = y2 val*ones(size(x)).x = x. Ypt(2. y2]). We are ﬁnally ready to solve this ode by %%%%% script m-file: nlode1 > > global which ode e >> global A >> which ode = 1. >> e = 3. The solution is contained in sol and is extracted by deval . 1.*(1 .x). 1. then do not use bvpinit. >> solinit = bvpinit(x. >> A = 1.*(1 . >> x = linspace(0.:).

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

x) where x can be a scalar. (−1.  .y) bvpinit(x. . If A is a square matrix. The polynomial can be evaluated at x by >> y = polyval(q. In conclusion. (0. For example.y) and boundary conditions(ya.5).  c2 . The user supplied functions are f(x. 2) and we want to ﬁnd the “best” ﬁt by a straight line. .8. bvpset bvpinit(x. Deﬁning the data points more abstractly as (xi .  . A) (See Section 15 for more details on this type of operation. . given the roots of a polynomial you can recover the coeﬃcients of the polynomial by >> q = poly(r) Warning: Note the order of the coeﬃcients in the polynomial.y soln) 12. . yi ) i = 1. However.. then p(A) = c1 An−1 + c2 An−2 + · · · + cn−1 A + cn is calculated by >> polyvalm(q. c1 is the coeﬃcient of the highest power of x and cn is the coeﬃcient of the lowest power. 2. you might well ﬁnd an ode for which this is not true.  .2. Polynomials and Polynomial Functions In MATLAB the polynomial p(x) = c1 xn−1 + c2 xn−2 + · · · + cn−1 x + cn .  . Suppose the data points are (−3. say = 1. −1). when = 0. . −2). a vector. . n and the desired straight line by y = c1 x + c2 . cn )T . <initial guess function>) deval(x. −0. the matrix equation for the straight line is     y1 x1 1  x2 1  c1  y2   . i. (Since the two odes are identical when = 1 you can use the solution you found to ode (11. .12. .1a) will converge to one of the two solutions and for the ode (11. is represented by the vector q = (c1 . . You can easily calculate the roots of a polynomial by >> r = roots(q) Conversely. (1. Boundary-Value Solver bvp4c(<right-hand side>. xn 1 yn 135 . these are passed to bvp4c when it is executed. and choose a “reasonable” initial guess. .e.) Then slowly decrease . Polynomials and Polynomial Functions with a “large” value of . b] with given boundary conditions and an initial guess for y . Assigns values to properties. <boundary conditions>.1a).yb) where ya = y(a) and yb = y(b). y) = right hand side(x. (1.01 we have y (0) ≈ 130 and when = 0.001 we have y (0) ≈ 1300.1b) will converge to the single solution. . = . Calculates the initial guess either by giving y directly or by using a function y = initial guess function(x). Interpolate to determine the solution at x . c2 . 1).) A practical example which uses polynomials is to ﬁnd the “best” ﬁt to data by a polynomial of a particular degree. 0. y) for x ∈ [a. we want to remind you that for the odes we have discussed here almost any “halfway reasonable” initial choice for the ode (11. <initial guess>) Numerically solves y (x) = f(x. or a matrix.

e. y = c1 xm + c2 xm−1 + · · · + cm+1 . xn 1 1  . The statement >> V = vander(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 . yy. . Five of the interpolation methods which can be used are the following: nearest : The interpolated value is the value of the nearest data point. This entire procedure can be carried out much more easily by entering >> q = polyfit(x.2. c2 )T by >> c = [x ones(n. to make it easy for the function to determine which data points are “near” the desired value. o ) We can ﬁnd the “best” ﬁt by a polynomial of degree m < n . i.  . You can also ﬁnd a local maximum or minimum of the polynomial p(x) by ﬁnding the zeroes of p (x). cubic polynomials connect each pair of adjacent data points. (This is the default. . The coeﬃcients of p (x) are calculated by >> q deriv = polyder(q) where q is the vector of the coeﬃcients of p(x). This estimation is generally done by ﬁtting data which is “near” the desired value to a polynomial and then evaluating this polynomial at the value. enter >> V = vander(x) >> V(: . Given a set of data points (xi . You can also integrate a polynomial by >> q int = polyint(q) in which case the constant term is 0. Instead. by calculating the least-squares solution to Vc = y where  xm V=  . i. That is. linear : Linear splines are used to connect the given data points. Polynomials and Polynomial Functions In general. . 1:m-1) = []. .. and <method> is an optional argument specifying the method to be used. That is. we ﬁnd the least-squares solution c = (c1 . −1 xm n ··· ··· ··· x1 x2 . One additional requirement for this command is that the elements of x are monotonic. max(x). 1)] \ y We can plot the data points along with this straight line by >> xx = linspace(min(x). c) for some constant c in which case the constant term is c. x. generates the square Vandermonde matrix with m = n − 1.12. xx). For example. xm n 1  xm 2 m−1 x1 m−1 x2 . . either all in increasing order or in decreasing order.   cn The matrix V is called a Vandermonde matrix . . y.. The simplest command in one dimension to interpolate the points (xi . <method>) where xvalues is a vector of the values to be interpolated. Warning: The Vandermonde matrix is approximately as badly conditioned as the Hilbert matrix which was discussed in Section 5. 100). >> yy = polyval(c. m-1) where the third argument is the order of the polynomial (i. 1  c1  c2  .) spline : Cubic splines are used to connect the given data points.e. >> plot(xx. yi ) 1 ≤ i ≤ n is >> yvalues = interp1(x. and c =   . 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). To generate the n×(m − 1) Vandermonde matrix we want. y. . There are a number of commands to interpolate data points in any number of dimensions. yvalues is the vector of the interpolated values. the number of coeﬃcients in the polynomial). xvalues. cond(vander([1 : 10])) = 2×1012 whereas cond(hilb(10)) = 2×1013 . there is no solution to this overdetermined linear system. or by >> q int = polyint(q.e. . y.

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

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

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

e. If R is the resistance in the circuit. is Pk = |a0 |2 1 2 if k = 0 2 2 |ak | + |bk | if k > 0 and the frequency of the k th mode is k/T cycles per unit time. ∞) . where I is the current and t is the time it takes for the charge to move between the two terminals.. if we consider f (t) to be the voltage or the current of some signal. cos αt = 2 2i we can rewrite the real Fourier series as the complex Fourier series ∞ f (t) = a0 + k=1 1 2 (ak −2πikt/T − ibk )e2πikt/T + 1 2 (ak + ibk )e so that f (t) = ∞ ck e2πikt/T k=−∞ for all t ∈ [0. However.14. Since eiαt − e−iαt eiαt + e−iαt and sin αt = . . a1 . Next. b2 . and ak and bk are the coeﬃcients of the k th mode. The power of the function f (t) is† P = so that P = |a0 |2 + 1 2 1 T T f (t) 0 2 dt ∞ |ak |2 + |bk |2 . consider a charge q which is moving between two terminals having a potential diﬀerence of V .2) 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 r is the vector from P0 to P1 . The coeﬃcients a0 . . are called the real Fourier coeﬃcients of f . The work done on the charge is W = qV = ItV . a2 . we begin with the deﬁnition of work. . The power of the particle is the work done per unit time. If the particle moves from the point P0 to P1 then the work done to the particle is F q r . and b1 . To understand the physical signiﬁcance of power.. 141 . the power spectrum. . V = IR and the power is W V2 = IV = I 2 R = . t R Thus. the instantaneous power in the signal is proportional to f 2 (t) and the average power is proportional to P = 1 T T f (t) 0 2 dt . Discrete Fourier Transform where a0 = 1 T 0 T f (t) dt T 0 T 0 2 ak = T 2 bk = T    f (t) cos kt dt     f (t) sin kt dt   for k ∈ N[1. k=1 The power in each mode. . . we will stick to the common usage. F q v where v = r/t . T ] (14. i.e. Consider a particle which is under the inﬂuence of the constant force F . i.

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

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

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

Note: When N is even we cannot recover γM and so we only know one of the two coeﬃcients of the M th mode. we can reorder them by using fftshift . M − 1 . Clearly. . We plot the periodic unperturbed signal. . g ) (which is contained in the accompanying zip ﬁle). . vs. We begin with %%%%% script m-file: fft ex1 time = 0. the Fourier coeﬃcients are calculated by >> fc = fft(f)/N The coeﬃcients of the discrete Fourier transform are now contained in fc as fc = γ0 . is again recovered by >> f = N*ifft(fc) Note: Since there are now an even number of Fourier coeﬃcients. M − 2. . y0 . r ). γ0 . ypert . We now look at the Fourier spectrum of y0 by plotting the power at each frequency in 145 . γ1 . time. N = 600. . Also. time. γ−M +1 . N). . This is a signal at 50 and 120 hertz (cycles per unit time). represented by the vector f . it occasionally happens that this causes diﬃculties. % perturbed signal figure(1) plot(t. γ−2 . we cannot determine the M th mode correctly. which is perturbed by adding Gaussian noise. Discrete Fourier Transform and the discrete Fourier coeﬃcients are calculated by γk = 1 N N −1 fj e−2πijk/N j =0 for k = −M. . . γ1 . The result is fftshift(fc) = γ−M . T . γM −1 . y0.14. γ−2 . which switches the ﬁrst half and the last half of the elements. f1 . . given f = (f0 . y0 = sin(2*pi*50*t) + sin(2*pi*120*t). We show a simple example of the use of Fourier coeﬃcients from The Student Edition of MATLAB: User’s Guide. γ−1 T . γM −1 . ypert. As before. . % unperturbed signal ypert = y0 + 2*randn(size(t)). fN −1 )T . Thus. . γ−M +1 . γ−M . The solution is to set γ−M = 0 so that the M th mode is dropped completely. ifftshift is the same as fftshift if N is even. . γ−1 . . . Although we cannot give a simple example. . . . the original signal has been completely lost — or has it. f2 . . 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 . axis([0 time -8 8]) hold on pause(1) plot(t. . and then the perturbed signal. . . The original function. γM −2 . t = linspace(0.6. . −M + 1. γM −2 . once the random noise has been added. . .

Thus. g ) (which is contained in the accompanying zip ﬁle). freq . power0. t. which makes clear how large the perturbation is. state that it is an odd function. (For simplicity in the discussion.e. and then the perturbed power. ychop.1. the frequency at each mode.. 2. % delete k = N/2 +1 mode power0(1) = abs(fc0(1)).14.5]) fcpert = fft(ypert)/N.) Clearly. Let us see if we can reconstruct the original signal by removing any mode whose magnitude is “small”.1 ). 2 + abs(fc0(N-1:-1:N/2 +1)). T ] or for t ∈ [−1/2 T. % Fourier spectrum of perturbed signal hold on powerpert(1) = abs(fcpert(1)). If f (t) is an odd function in t . 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. powerpert(2:N/2) = abs(fcpert(2:N/2)). the inverse Fourier transform returns a “slightly” complex result. then the real trigonometric series can be simpliﬁed to ∞ 2πkt f (t) = bk sin T k=1 for t ∈ [0. power0 . Discrete Fourier Transform %%%%% script m-file: fft ex2 fc0 = fft(y0)/N. but the random noise has excited every mode. First. 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. r . % where fcchop should be ip(N:-1:N/2 +2) = ip(2:N/2). whose power is less than this value. except for those corresponding to the spikes. ( ychop is the real part of N*ifft(fcchop) because. We discretize this inﬁnite series by n fdst (t) = k=1 bk sin 146 2πkt T . 1/2 T ] and. axis([0 freq(N/2) 0 . we see that the power in all the modes. we call this new Fourier spectrum fcchop . % signal of "chopped" Fourier spectrum figure(1) plot(t. the original spikes are still dominant. By looking at the power plots. i. ychop. % initialize the chopped Fourier spectrum ip = zeros(size(fcpert)). freq = [1:N] /time. enter >> sum(power0) >> sum(powerpert) The perturbed signal has about ﬁve times as much power as the original signal. we plot the unperturbed power. To see how much power is in the unperturbed signal and then the perturbed signal. have an amplitude 0.) The result is remarkably good considering the size of the perturbation. due to round-oﬀ errors. 2. power0(2:N/2) = abs(fc0(2:N/2)). b ) ˆ ˆ ˆ ˆ ˆ ˆ ˜ (which is contained in the accompanying zip ﬁle). 2 + abs(fcpert(N-1:-1:N/2 +1)). powerpert . we only need deﬁne f (t) for t ∈ [0. 2. % Fourier spectrum of unperturbed signal figure(2) fc0(N/2 +1) = []. % the frequency of each mode plot(freq(1:N/2). +1/2 T ]. The two spikes in the plot of the unperturbed power are precisely at 50 and 120 hertz.e. y0. 2. i. % zero out "small" modes ychop = real( N*ifft(fcchop) ).. additionally. Choosing the latter interval. fcpert . f (−t) = −f (t) for all t . r ). % construct a vector with 0’s ip(1:N/2) = ( powerpert > 0. pause(1) plot(freq(1:N/2). powerpert. the signature of the two sine functions in y0 . % zeroed out fcchop( find( ip) ) = 0. vs. b ) figure(3) plot(t. we delete any mode of the perturbed Fourier spectrum.

) If A is a square diagonal matrix eA is particularly simple to calculate since    p  p a11 a11 p a22 a22     . 2. . f = dst(b) . f (tn ) dst and idst switch between them by >> f = dst(b) >> b = idst(f) Discrete Fourier Transform fft(f) ifft(fc) fftshift(fc) ifftshift(cf) dst(b) idst(f) The discrete Fourier transform of f . . . (fftshift and ifftshift are the same if the number of elements is even. . . the MATLAB functions 15. T . n and the n data points ti . 1! 2! 3! (Thus. . = . . The inverse discrete sine transform so b = idst(f) . Recall that the solution of dy (t) = ay (t) dt for t ≥ 0 with y (0) = yic 147 . ean−1. . The discrete sine transform of f if it is an odd function where b are the coeﬃcients and f is the function. For example. .     p an−1. 1/2 T ] and we discretize this interval by 0 = t0 < t1 < · · · < tn < tn+1 = 1/2 T where ∆t = 1 /2 T /(n + 1). Mathematical Functions Applied to Matrices for t ∈ [0. . Unswitches the ﬁrst half and the second half of the elements of fc .     Ap =  . . .) A simple example where eA occurs is in the solution of ﬁrst-order ode systems with constant coeﬃcients. f (t2 ). This leaves i = 1.n−1 an−1. (Otherwise. since a2 a3 a + + ··· ea = 1 + + 1! 2! 3! we deﬁne eA to be A A2 A3 eA = 1 + + + + ··· . us with the n coeﬃcients bi i = 1. .n−1 ann ap nn 0 0 0 0 Thus. mathematical functions can generally only be applied to square matrices. That is. Mathematical Functions Applied to Matrices As we brieﬂy mentioned in Section 2.n−1 0 eann    .  0 The MATLAB command >> expm(A) calculates eA if A is a square matrix. if A ∈ Cm×n where m = n then eA does not exist because Ak does not exist if A is not a square matrix. it generates an error message. That is.7. . Switches the ﬁrst half and the second half of the elements of fc .15. . We immediately have f (t0 ) = f (tn+1 ) = 0 so these two nodes are not needed. . 2. The inverse discrete Fourier transform of the Fourier coeﬃcients fc . . if A ∈ Cn×n then eA is deﬁned from the Taylor series expansion of ea . bn )T and f = f (t1 ). . b2 .    e =  A ea11 ea22 . f (ti ) Deﬁning the vectors b = (b1 . . n . .   .

. . = . there is a general matrix function for the other mathematical functions. and cosh as well as user-deﬁned functions.. ···   y (t)  a1n 1 a2n   y2 (t)   . eA where A must be a square matrix. dt  . . the solution of  y (t)   a11 1 y2 (t)   a21 d   ..  . This √ would be much more costly than simply using the analytical solution. . Mathematical Functions Applied to Matrices is y (t) = yic eat . . log B is calculated in MATLAB by entering >> logm(A) These are the only explicit MATLAB commands for applying mathematical functions to matrices. .e. an1 yn (t) i. ann yn (t) y(t) = eAt yic . as discussed in Section 10.15.  . to solve it. an2 ··· ··· . However. Similarly. √ A where A must be a square matrix.   . for t ≥ 0 with y(0) = yic To calculate y(t) for any time t . y (t) = Ay(t). Similarly. is a12 a22 . 10] in order to obtain a numerical approximation at the ﬁnal time. . The command >> funm(A. 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. Matrix Functions expm(A) sqrtm(A) logm(A) funm(A. B is calculated in MATLAB by entering >> sqrtm(A) Finally. <function handle>) evaluates <function name>(A) for the MATLAB functions exp . cos . you would have to solve the ode for all t ∈ [0. log A where A must be a square matrix. <function handle>) Calculates Calculates Calculates Calculates matrix. However. <function name>(A) where A must be a square 148 . sinh .  . sin .

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

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

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

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

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

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

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

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

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

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

Appendix: Reference Tables

Logical Functions all any exist isequal find ischar isempty isfinite isinf islogical isnan logical True if all the elements of a vector are true; operates on the columns of a matrix.(p. 100) True if any of the elements of a vector are true; operates on the columns of a matrix.(p. 100) False if this name is not the name of a variable or a ﬁle.(p. 100) Tests if two (or more) arrays have the same contents.(p. 100) The indices of a vector or matrix which are nonzero.(p. 100) True if a vector or array contains character elements.(p. 100) True if the matrix is empty, i.e., [] . (p. 100) Generates a matrix with 1 in all the elements which are ﬁnite (i.e., not Inf or NaN ) and 0 otherwise.(p. 100) Generates a matrix with 1 in all the elements which are Inf and 0 otherwise.(p. 100) True for a logical variable or array.(p. 100) Generates a matrix with 1 in all the elements which are NaN and 0 otherwise.(p. 100) Converts a numeric variable to a logical one.(p. 100)

Programming Language Functions echo end error eval feval function global lasterr persistent keyboard nargin nargout return varargin varargout Turns echoing of statements in m-ﬁles on and oﬀ.(p. 112) Ends a function. Only required if the function m-ﬁle contains a nested function.(p. 95, 112) Displays the error message and terminates the function.(p. 112) Executes MATLAB statements contained in a text variable.(p. 114) Executes a function speciﬁed by a string.(p. 114) Begins a MATLAB function.(p. 112) Deﬁnes a global variable (i.e., it can be shared between diﬀerent functions and/or the workspace).(p. 112) If eval “catches” an error, it is contained here.(p. 114) Deﬁnes a local variable whose value is to be saved between calls to the function.(p. 112) Stops execution in an m-ﬁle and returns control to the user for debugging purposes.(p. 106) Number of input arguments supplied by the user.(p. 112) Number of output arguments supplied by the user.(p. 112) Terminates the function or script m-ﬁle immediately.(p. 106, 112) “Groups” input arguments together.(p. 112) “Groups” output arguments together.(p. 112)

159

Appendix: Reference Tables

Debugging Commands keyboard dbstep dbcont dbstop dbclear dbup dbdown dbstack dbstatus dbtype dbquit return Turns debugging on.(p. 106) Execute one or more lines.(p. 106) Continue execution.(p. 106) Set a breakpoint.(p. 106) Remove a breakpoint.(p. 106) Change the workspace to the calling function or the base workspace.(p. 106) Change the workspace down to the called function.(p. 106) Display all the calling functions.(p. 106) List all the breakpoints.(p. 106) List the current function, including the line numbers.(p. 106) Quit debugging mode and terminate the function.(p. 106) Quit debugging mode and continue execution of the function.(p. 106, 112)

Discrete Fourier Transform fft fftshift ifft fftshift dst idst The discrete Fourier transform.(p. 147) Switches the ﬁrst half and the second half of the elements of a vector.(p. 147) The inverse discrete Fourier transform.(p. 147) Unswitches the ﬁrst half and the second half of the elements of a vector.(p. 147) The discrete sine transform.(p. 147) The inverse discrete sine transform.(p. 147)

Sparse Matrix Functions speye sprand sprandn sparse spdiags full find nnz spfun spy spconvert Generates a Sparse identity matrix.(p. 120) Sparse uniformly distributed random matrix.(p. 120) Sparse normally distributed random matrix.(p. 120) Generates a sparse matrix elementwise.(p. 120) Generates a sparse matrix by diagonals.(p. 120) Converts a sparse matrix to a full matrix.(p. 120) Finds the indices of the nonzero elements of a matrix.(p. 120) Returns the number of nonzero elements in a matrix.(p. 120) Applies the function to a sparse matrix.(p. 120) Plots the locations of the nonzero elements of a sparse matrix.(p. 120) Generates a sparse matrix given the nonzero elements and their indices.(p. 120)

160

Appendix: Reference Tables

Time Evolution ODE Solvers ode45 ode23 ode113 ode15s ode23s ode23t ode23tb ode15i odeset Non-stiﬀ ode solver; fourth-order, one-step method for the ode y = f(t, y). (p. 122) Non-stiﬀ ode solver; second-order, one-step method.(p. 122) Non-stiﬀ ode solver; variable-order, multi-step method.(p. 122) Stiﬀ ode solver; variable-order, multi-step method.(p. 122) Stiﬀ ode solver; second-order, one-step method.(p. 122) Stiﬀ ode solver; trapezoidal method.(p. 122) Stiﬀ ode solver; second-order, one-step method.(p. 122) Stiﬀ ode solver; variable-order, multi-step method for the fully implicit ode f(t, y, y ) = 0 . (p. 131) Assigns values to properties of the ode solver.(p. 126)

Boundary-Value Solver bvp4c bvpset bvpinit deval Numerically solves y (x) = f(x, y) for x ∈ [a, b] with given boundary conditions and an initial guess for y . (p. 135) Assigns values to properites of bvp4c . (p. 135) Calculates the initial guess either by giving y directly or by using a function y = initial guess function(x). (p. 135) Interpolate to determine the solution desired points.(p. 135)

Numerical Operations on Functions dblquad fminbnd fminsearch optimset fzero quad quadgk Numerically evaluates a double integral.(p. 140) Numerically calculates a local minimum of a one-dimensional function.(p. 140) Numerically calculates a local minimum of a multi-dimensional function.(p. 140) Allows you to modify the parameters used by fzero , fminbnd , and fminsearch . (p. 140) Numerically calculates a zero of a function.(p. 140) Numerically evaluates an integral using Simpson’s method.(p. 140) Numerically evaluates an integral using the adaptive Gauss-Kronrod method. The interval can be inﬁnite and/or the function can have an integrable singularity.(p. 140) Numerically evaluates an integral using the adaptive Gauss-Lobatto method.(p. 140)

161

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

5) 2.:) = (-9/5)*A(2.1) ˆ 1. 4 5 6.7a) ˆ A = [ ones(6.10. and 4.5 % or C = sqrt(A) A A % or mean(R(:)) b) ˆ ˆ B 2 ˆ C.(2*cos(th) 2 . 1.7.2e20 .3) 2.10.4a) b) 2. cos(2*th) .1).6850e+06i ˆ ˆ > > th = input( th = ).ans > > (1. 2.9.10.9. ab = 79. A(1.4) zeros(6) ].diag( ones(n-1.:) + A(3.1i*12 20) (1/3) answer: 1.6a) b) c) d) e) 2.4) help fix or doc fix . -1 ) A = diag([1:n].1). 7 8 10] B = A .9.1) = 5.3) > > diary triangle.10) = -5 A = A .7.2*a*b*cosd(ab)) > > format long > > c answer: 6.3637e+07 .Solutions To Exercises These are the solutions to the exercises given in subsections 1. 13:16] A = [ [1:4:13] [2:4:14] [3:4:15] [4:4:16] ] A(2. 13 14 15 16] A = [1:4. 5 6 7 8. 1 ) .:) A = 4*eye(n) . 2 ˆ % or x = [0:30].6. c = sqrt(a 2 + b 2 . 2 ˆ R = rand(5) [m.1a) > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > A = [1 2 3 4. -1 ) b) 2.2) 1.tril(A. 2) . 9 10 11 12. 5:8. 2.10. A(6.10.diag( ones(n-1. 3.1).9. .10.7.1751 ˆ b 2 ˆ . b = 5.5 % or B = sqrtm(A) C = A.-1) x = [0:30] .2) 2.9.9448e+01 format short e asin( (b/c)*sin(ab*deg) ) / deg c) d) 1. 1 ) . deg = pi/180.10.7. 2 ˆ 163 .10.175085147187636 > > > > or > > asind( (b/c)*sind(ab) ) answer: 4.diag( exp([2:n]).1a) or > > answer: b) > > > > a = 3.diag( ones(n-1. im] = max(R ) mean(mean(R)) S = sin(R) r = diag(R) A = [1 2 3.2*a*b*cos(ab*deg)) + ˆ c = sqrt(a 2 ˆ 6. 9:12.

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

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

Solutions To Exercises 166 .

Semicolon < Less than sign = Equal sign > Greather than sign ? Question mark Octal 100 101 102 103 104 105 106 107 110 111 112 113 114 115 116 117 120 121 122 123 124 125 126 127 130 131 132 133 134 135 136 137 140 141 142 143 144 145 146 147 150 151 152 153 154 155 156 157 160 161 162 163 164 165 166 167 170 171 172 173 174 175 176 177 Decimal 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 Description @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] AT symbol ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ˜ ˆ ‘ a b c d e f g h i j k l m n o p q r s t u v w x y z { | } Left bracket Back slash Right bracket Caret Underscore Opening single quote ˆ? Left brace Vertical bar Right brace Tilde Delete American Standard Code for Information Interchange (ASCII) speciﬁes a correspondence between bit patterns and character symbols. The octal and decimal representations of the bit patterns are shown along 167 .ASCII Table ASCII Table Control Sequence Control Sequence Octal 000 001 002 003 004 005 006 007 010 011 012 013 014 015 016 017 020 021 022 023 024 025 026 027 030 031 032 033 034 035 036 037 040 041 042 043 044 045 046 047 050 051 052 053 054 055 056 057 060 061 062 063 064 065 066 067 070 071 072 073 074 075 076 077 Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 Description Null character Start of header Start of text End of text End of transmission Enquiry Acknowledgment Bell Backspace Horizontal tab Line feed Vertical tab Form feed Carriage return Shift out Shift in Data link escape Device control 1 (often XON) Device control 2 Device control 3 (often XOFF) Device control 4 Negative acknowledgement Synchronous idle End of transmissions block Cancel End of medium Substitute Escape File separator Group separator Record separator Unit separator Space ! ” Double quote # Numer sign \$ Dollar sign % Percent & Ampersand ’ Closing single quote (apostrophe) ( Left parenthesis ) Right parenthesis * Asterisk + Plus sign . Comma Minus sign or dash . Dot / Forward slash 0 1 2 3 4 5 6 7 8 9 : Colon .

decimal 10 ended a line on a line printer and decimal 8 backspaced one character so that the preceding character would be overstruck.ASCII Table with a description of the character symbol. The ﬁrst 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 provide 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. ˆ 168 .

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

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

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

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

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

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

Erase (a .

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

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

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

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

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

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

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

Index 182 .