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

1:17 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 49 50 50 59 62 67 69 75 78 78 79 82 83 84 86

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

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

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

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

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

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

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

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

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

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

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

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

92 92 97 101 114 115 118 121 121 126 132 136 139 141 148 151 151 151 152 152 152 153 154 154 155 155 155 156 156 157 157 158 159 159 160 160 160 161 161 162 162 162 163 163 163 164 164 165 169 171

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

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

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

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.

**but instead you type
**

8

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

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

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

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

arccos x. y > 0. y) rem(x.6. arcsec x where the result is in degrees. arcsin x where the result is in degrees. 13 . arccosh x. arcsec x.. The common log of x. tanh x. 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. and if x = 0 this returns 0.e. n! for n a non-negative integer.4*a*c ) ) / (2*a) >> x2 = ( -b . If x ≥ 0 this is the largest integer which is ≤ x.. tan x. csch x.0000i and ˆ ˆ † This function is in the symbolic math toolbox. coth x. For example. arcsin x. cot x. if x < 0 this returns 0. If x < 0 this is the smallest integer which is ≥ x. arctan x where the result is in degrees. sec x. arctan y/x where the angle is in (−π. i. and if x = 0 this returns 1/2 . Complex Numbers MATLAB can work with complex numbers as easily as with real numbers. log10 x. cosh x. That is. The smallest integer which is ≥ x. arctan x. sin x. arccsc x. The integer which is closest to x. the code is shown on page 105. √ x. If x > 0 this returns +1. arccot x where the result is in degrees. log(x + 1). sec x where x is in degrees. cot x where x is in degrees. +π]. x − n ∗ y where n = floor(x/y). arccot x. ex . expm1(x) factorial(n) fix(x) ex − 1.0000 + 2. sin x where x is in degrees. arccsch x.4*a*c ) ) / (2*a) The output is -1. The modulus after division. If x > 0 this returns 1. >> x1 = ( -b + sqrt( b 2 . This is the largest integer which is ≤ x. arcsech x. arctanh x. floor(x) heaviside(x)† log(x) log10(x) log1p(x) mod(x. loge x. 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. If it is not on your computer.1.e. sinh x.6. c = 5. arcsinh x. i. cos x. Warning: be careful if x < 0. The remainder of x/y. b = 2. cos x where x is in degrees. tan x where x is in degrees. arccsc x where the result is in degrees. csc x. arccos x where the result is in degrees. csc x where x is in degrees. The natural log of 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. arccoth x. This is the same as mod(x. sech x. y) if x. to ﬁnd the roots of the quadratic polynomial x2 + 2x + 5 enter >> a = 1. if x < 0 this returns −1.sqrt( b 2 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2. a). incidentally. Manipulating Matrices >> Y = bsxfun(@plus. <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 . X. 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. b).3. is much faster than using repmat. it then outputs a column vector of the same size as the input. A. 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. but we will only describe it for bsxfun(<function handle>. 27 . This command can actually be applied to multidimensional matrixes. which.

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

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

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

This command returns the CPU time in seconds that have been used since you began your MATLAB session. Note: This is very diﬀerent from using cputime. i. † 31 . the order in which it evaluates an expression. inv(rand(n)). The following table shows the precedence of all MATLAB operators. The solution to xA = b where x and b are row vectors. That is. You can also calculate the wall clock time required for some sequence of commands by using tic and toc . 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. The CPU. Instead.2. is the “guts” of the computer. the hardware that executes the instructions and operates on the data. in which order does MATLAB do the calculations? For example. The solution to Ax = b by Gaussian elimination when A is a square nonsingular matrix. B. Arithmetical Matrix Operations A+B A-B A*B A n A\b Matrix addition. Operators with the same precedence are evaluated from left to right in an expression. the elapsed time might be much less. B A. Matrix exponentiation. 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. A.\A Elementwise multiplication. >> n = input( n = )./B B.e. Central Processing Unit. The solution to XA = B by Gaussian elimination. that is. if an expression uses two or more MATLAB operators. For example. time = cputime. Operator Precedence appeared in version 6. This time is frequently diﬃcult to calculate. Returns the elapsed time between these two commands. Here is a simple example to determine the CPU time required to invert a matrix. cputime . tic followed by toc is exactly the same as if you had used a stopwatch to determine the time. p p. The solution to AX = B by Gaussian elimination. A\B b/A B/A cputime tic.*B A. >> tic.\A is exactly the same as A. The precedence is from highest to lowest. on a multiprocessor computer.5. that is. we can calculate the amount of CPU time† required to execute a command by using cputime. A A. <sequence of commands>. Matrix subtraction. Elementwise exponentiation. toc Approximately the amount of CPU time (in seconds) used during this session.5. Elementwise left division. Matrix multiplication. the elapsed time might be much greater than the CPU time. Operator Precedence It is important to list the precedence for MATLAB operators./B. On the other hand.. ˆ ˆ ˆ ˆ Elementwise division. 2.time Warning: Remember that you have to subtract the CPU time used before the operation from the CPU time used after the operation. toc returns the time in seconds for this sequence of commands to be performed. 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.0000 0. † 32 . (We discuss eigenvalues in Section 7.. “ :” has higher precedence than “ +” and so 1:n+1 is (1:n)+1 ≡ 2:(n+1)./ . in the statistical computer languages R and S (which are somewhat similar to MATLAB).† Also.6. ∗ .6.. Be Careful! Be very careful: occasionally you might misinterpret how MATLAB displays the elements of a vector or matrix. . [unary minus] .. for example.. i. 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 . / ..0114 0.e. Thus.) der 5. > . \ + [addition] . if it was zero MATLAB would display 0 and not 0. x = 5 + 1 and x = 10 − 13.. & | && || ˆ ˆ ˜ ˜= The unary plus and minus are the plus and minus signs in x = +1 and x = −1. Entering >> format short e >> ans On the other hand. >= .. .....0003 0. ..2) enter >> format short >> eig(hilb(5)) MATLAB displays the eigenvalues as the column vector ans = 0. (we discuss this matrix in detail in Section 5. . + [unary plus] .0000...2.2085 1.\ . For example. The plus and minus signs for addition and subtraction are. 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 ( . A*C\b = (A*C)\b because “ *” and “ \” have the same precedence and so the operations are evaluated from left to right..∗ .. ) . the MATLAB command eig calculates the eigenvalues of a square matrix. . 1:n+1 is 1:(n+1) because “ +” has higher precedence than “ :”... . . − [subtraction] : < . == . <= .5671 You might think the the ﬁrst element of this vector is 0. However.

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

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

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

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

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

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

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

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

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

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

>> 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. 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. then its value is . For example. Thus.xed when the function is deﬁned.

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

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

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

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

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

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

MATLAB has 15 fundamental classes.5. otherwise. use the function class. A simple template for generating a new class is 47 . we now list them all. Warning: Caveat Emptor! The procedures for combining diﬀerent numerical classes is very diﬀerent from other programming languages. 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.3.5 and value 0. MATLAB has user-deﬁned classes.e. which is an instance of the int8 class. which is an instance of the int32 class. similar to classes in object-oriented programming languages. To determine the class of a variable. In addition. each in the form of a matrix (from a 0×0 matrix up to an n dimensional matrix for any n ). and aj = 127. These logical values are each 1 byte. i. For completeness. Advanced Topic: Data Types and Classes A is > . Continuing the previous example. You can also determine if a variable has a particular class by using isa. >> class(i) returns int32 and >> isa(i. false.5 > > i = int32(3) > > j = int8(127) > > ai = a + i > > aj = a + j are ai = 9. For example. the results of > > a = 5.. to obtain an instance of the single class you can enter A = single(rand(5)) The same technique holds for all the numerical classes. int8 ) returns 0.

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

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

y3. -. Instead. Two-Dimensional Graphics and last elements are exactly the values entered into the command. and blue components in that order. xx. xx. the colors are deﬁned by giving the intensities of the red. x. which does not suﬀer from round-oﬀ errors because the colon operator is only applied to integers. y2..0100. y1.. solid line (default) dashed line dotted line dash-dot line Marker Description + o * . the second is a a green. and then the third by † As we discussed previously. dashed line with circles at the data points. 50 . x. y3.) In addition. x.) This is why we used the statement > > x = 2*pi*[0:n-1] /(n-1). r . type >> plot(x. g--o . y2. >> plot(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] . 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. mp ) plots three curves: the ﬁrst is a red. x. entering >> plot(y1) will result in a plot which is equivalent to >> plot([1:length(y1)]. you can use small asterisks to show the locations of the data points for the y3 curve by >> plot(x. the third has magenta pentagrams at the data points but no line connecting the points. y2. We can also plot the ﬁrst curve. above. :* ) These strings are used to modify the color of the line. x. green.) Note: The plot function can even have only one argument. (As we discuss later in this section. : ) where “ --” means a dashed line and “ :” means a dotted line.01 : 0.1.02-eps] is 0 0. to return n − 1 elements rather than n. -.† To put all the curves on one plot. the output of [0 : 0. y3) Each curve will be a diﬀerent color — but this will not be visible on a black-and-white output device. y2. (We list all these symbols in the following table. For example. to put markers at the nodes. solid line. 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 -: -. y1. and to modify the type of line as shown in the table below. (For example.4. y3. xx. you can change the type of lines by >> plot(x. y1. y1. and then add the second.

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

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

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

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

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

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

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

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

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

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 4 4 4 1 2 3 5 5 5 1 2 3 X= , Y= 6 6 6 1 2 3 7 7 7 1 2 3 while >> [X, Y] = ndgrid(1:3, 4:7) returns 1 X = 2 3

1 2 3

1 2 3

4 1 2 , Y = 4 3 4

5 5 5

6 6 6

7 7 7

60

4.3. Advanced Topic: Commands

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.

Advanced Topic: Commands

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

4.3. Advanced Topic: Commands

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

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

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

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

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

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

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

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

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

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

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

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

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

w). break. plothandle = plot(i. Xprev2 = X. p = -1:1. Xprev = X.MAXIMUM NUMBER OF ITERATIONS EXCEEDED ) break end end M = close(M). file name = [ life movie . for. iseed).e) + X(n. X = (X & (N == 2)) | (N == 3). while true N = X(n.e) + X(:.4.:) + X(:. 12). nr iter = nr iter + 1.w) + X(n. if. j] = find(X).:) + X(s. F). M = avifile( life movie. MarkerSize . Inc. j. m). num2str(nr iter. num2str(nr iter)]) axis([0 m+1 0 m+1]). [i. title([ # iter = .. M = addframe(M. file name). %06d ).jpg ]. %06d ). X(kx+p.) 75 . Red . while.4)*rand(1)) + 2. s = [2:m 1].jpg ]. for count = 1:15 kx = floor((m .4)*rand(1)) + 2. e = [2:m 1]. % modify seed to obtain different cells rand( state . xdata . num2str(nr iter..6. M = addframe(M. j) title([ # iter = .j] = find(X). set(plothandle. saveas(gcf. max nr iter = 10000. num2str(nr iter)]) drawnow F = getframe(gcf). m = 26.w) + . w = [m 1:m-1].e) + X(s.5). .avi ). %%%%% script m-file: sample movie % modified from the MATLAB function life which is % Copyright 1984-2004 The MathWorks. Warning: This code uses a number of MATLAB commands which have not been yet discussed: sparse. . drawnow F = getframe(gcf). ydata . Advanced Topic: Making Movies must be used to compress it. if X == Xprev2 break else Xprev2 = Xprev. i. figure(gcf). Color . . file name). saveas(gcf. Xprev = X. n = [m 1:m-1]. find. . F). and logical expressions. ky = floor((m . [i. end if nr iter > max nr iter disp( EXIT . % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 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. file name = [ life movie . X(s. X = sparse(m. nr iter = 0.ky+p) = (rand(3) > 0. end. iseed = 3343.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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. Numerically evaluates an integral using the adaptive Gauss-Kronrod method. We are presenting the material in such detail because there are a few slightly diﬀerent deﬁnitions of the discrete Fourier transform. Numerically evaluates an integral using the adaptive Gauss-Lobatto method. <Value 1>. 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. a. a. xmin. ymin. a. ymax) It can also calculate the triple integral xmax xmin ymax ymin zmax f (x. T ] (14. xmin. z) dxdy dz zmin by >> triplequad(<function handle>. Numerically calculates a zero of a function given the initial iterate. iterate0) fzero(<function handle>.. . MATLAB can also calculate the double integral xmax xmin ymax f (x. Discrete Fourier Transform >> g = @(x) exp(sqrt(x))/sqrt(x). zmin. ymax. 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.) quad(<function handle>. b) quadgk(<function handle>. fminbnd. b. y. 1) is −2. ymin. x0 can be replaced by a 2vector of the endpoints of the interval in which a zero lies. c. xmax. xmax) Numerically evaluates a double integral. The interval can be inﬁnite and/or the function can have an integrable singularity.14. we present the deﬁnition which follows directly from the real Fourier series. x0) optimset <Prop 1> . xmin.3670×10−13 (the actual value is 2(e − 1) ). Discrete Fourier Transform There are a number of ways to deﬁne the discrete Fourier transform. Allows you to modify the parameters used by fzero.1) . b) quadl(<function handle>. and fminsearch. 0. b) 14. a. we choose to deﬁne it as the discretization of the continuous Fourier series. Numerically evaluates an integral using Simpson’s method.. zmax) Numerical Operations on Functions dblquad(<function handle>. fminsearch(<function handle>. d) fminbnd(<function handle>. >> quadgk(g. y) dxdy ymin by >> dblquad(<function handle>.

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

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

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

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

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

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

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

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

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

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

(p.(p.(p. (p. 13) Inverse tangent (result in degrees).(p. 13) sign The sign of the real number.x) is the angle (in (−π.(p. 13) csc Cosecant. 13) Cosine (argument in degrees).(p.(p. 13) coth Hyperbolic cotangent. 14) log The natural logarithm. 13) Inverse cotangent (result in degrees). i. 13) factorial Factorial function. 13) log1p(x) log(x + 1). 13) Hyperbolic cosine. 13) Inverse sine (result in degrees). (p. 13) sec Secant. 13) round Round to the closest integer.(p.(p.(p.e. 13) Inverse cotangent.(p. 13) secd Secant (argument in degrees).(p.(p.(p.(p.(p. 13) Inverse tangent.(p.. 13) exp Exponential function.(p.(p. 13) Round upward to the nearest integer.(p.(p.(p. 13) Inverse hyperbolic cosine.(p.(p.(p. 13) cotd atanh ceil conj cos cosd cosh cot 151 . to the base 10. 13) Inverse hyperbolic sine. 13) cscd Cosecant (argument in degrees). 13) real The real part of a complex number.(p. 13) Cotangent (argument in degrees).(p. 13) fix Round toward zero to the nearest integer. 14) Inverse cosine. 13) sinh Hyperbolic sine. 13) expm1(x) ex − 1.(p.(p. 13) sqrt Square root.(p. 13) tand Tangent (argument in degrees). (p. 13) Inverse hyperbolic tangent.(p.(p.(p. y). 13) tanh Hyperbolic tangent. 13) Inverse cosecant (result in degrees). (p. 13) Inverse hyperbolic cosine.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) heaviside The Heaviside step function. 13) floor Round downward to the nearest integer. i.(p. 13) sin Sine. 13) Inverse hyperbolic cosecant. (p. 13) Inverse tangent using two arguments where atan2(y..(p. 13) Inverse cosine (result in degrees). +π] ) from the positive x axis to the point (x. 13) sech Hyperbolic secant.(p.e. 13) Cotangent.(p. 13) log10 The common logarithm.(p. 13) Phase angle of a complex number. 13) sind Sine (argument in degrees). 14) Inverse secant. 13) Inverse hyperbolic secant.(p. 13) tan Tangent.(p.(p.(p. 13) Inverse secant (result in degrees). 14) rem The remainder after division.(p. to the base e. 13) mod The modulus after division. 13) Complex conjugation.(p.(p.(p. 13) Inverse sine.(p. 13) csch Hyperbolic cosecant. 14) Cosine.(p.(p. 13. 13) Inverse cosecant. 13) imag The imaginary part of a complex number.(p.(p.

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

(p. 120) Sparse normally distributed random matrix.(p.(p. n. 22) Specialized Matrices hilb vander toeplitz Generates the hilbert matrix. 120) Sparse uniformly distributed symmetric random matrix.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) conjugate transpose of a matrix. 28) Elementary Matrix Operations size numel(A) length . 120) Generates a logical matrix with all elements having the value true. The The The The The size of a matrix. 22) Generates a logical matrix with all elements having the value false. 22) total number of elements in a vector or matrix. ) number of elements in a vector. 22) 153 . .(p. (Deﬁned on p.e.(p. 22) Uniformly distributed random integers. (p. 22) Generates a random permutation of the integers 1. (p.(p. 2. 22) transpose of a matrix. 22) Generates a Sparse identity matrix. 137.. (Deﬁned on p. 1). 120) Sparse uniformly distributed random matrix. 22) Generates a seed for the random number generator.(p.(p. (p. . 95) Generates a zero matrix.(p.(p.(p. (p.(p. 82.(p. 95) Generates a matrix with all elements being 1. .(p.) Generates a Toeplitz matrix (where the values are constant on each diagonal. the matrix can also be positive deﬁnite. Gaussian) distributed random numbers with mean 0 and standard deviation 1. 22) Generates a matrix whose elements are uniformly distributed random numbers in the interval (0.(p. .) Generates the Vandermonde matrix. 22) Generates a matrix whose elements are normally (i.

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

(p. 58) Generates logarithmically spaced points. 61) Generates a 2-D grid.(p. 58) 155 .(p. 61) Generates an “easy” 3-D ﬁlled-in surface. 58) Plots the data points in polar coordinates. i. 61) Plots a 3-D ﬁlled-in surface. 58) Plots a histogram.. ) Plots a step function. y(t) . 66) Raises the current graphics window so it is visible.(p.(p.(p.(p. 61) Fills one or more 3D polygons. x(t).(p.(p.(p. 58. 61) Plots a ﬁlled contour. 58) Generates an “easy” plot (similar to fplot ).(p.(p.(p. 58) Updates the current ﬁgure.(p.(p.(p.(p. 61) Adds a color bar showing the correspondence between the value and the color.e.(p. y) = 0. 61) Puts a label on the z-axis.(p. 61) Same as meshgrid except that the two arguments are reversed. 58) The same as plot but the y axis is logarithmic. f (x. 61) Plots a contour in 3-D. 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. 61) Divides the graphics window into rectangles and moves between them. 61) Generates an “easy” contour looking down the z axis. 58) The same as plot but both axes are logarithmic.(p..(p.(p.(p. 58) Generates an “easy” polar plot. 61) convert polar to cartesian coordinates.(p.(p. 58) Puts a label on the y-axis.(p. 58) Controls the scaling and the appearance of the axes.(p. 58) Plots a histogram given the number of elements in each bin. 66) The same as plot but the x axis is logarithmic. 58) Holds the current plot or release it.(p. similar to the colon operator.(p. (p.(p.(p. 58. i.(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.(p. 61) Generates an “easy” 3-D surface using a wire mesh. 66) Plots a 3-D surface using a wire mesh. 61) Changes the viewpoint of a 3-D surface plot. 58) Plots a curve through data points and also the error bar at each data point. 58) Divides the graphics window into rectangles and moves between them. 61) Plots a contour looking down the z axis.(p.(p.(p. 61) Label contour lines. 58) Puts a title on the top of the plot.e. 61) Generates an “easy” contour in 3-D. 61) Controls the scaling and the appearance of the axes. 61) Generates an “easy” plot in 3-D. 58) Fills one or more polygons. 61) Raises the current graphics window so it is visible.(p.(p.(p. or an implicit function. It can also plot a parametric function. 66) Determines the current color map or choose a new one.(p.(p.(p.(p. 58) Puts a label on the x-axis.(p. 58) Generates equally-spaced points.

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.(p.(p.(p. delete everything in the ﬁgure(p. 68) Invoke the GUI design environment to design your own GUI. 66) Plots a two-dimensional matrix and scales the colors. 66) Display an image. 68) The current ﬁgure handle.(p. 66) Plots a two-dimensional matrix.e.(p.(p. 77) 156 . or properties of an object. 66) Export an image to a graphics ﬁle.(p. 74) Resume execution of the GUI. 66) Clear a ﬁgure (i.(p.(p.(p.. 68) The current axes handle. 68) Sets the value of the property. 66) Runs demonstrations of many of the capabilities of MATLAB. 77) Play movie frames. 77) Close the ﬁle opened with avifile.(p.(p.(p.(p. 77) Add a frame to the avi ﬁle. 66) Import an image from a graphics ﬁle.(p. 17.(p.(p.(p.(p.(p.(p. 74) Create a new avi ﬁle.(p. 74) Create a user interface panel. 66) Obtains the current cursor position.(p.(p. 66) Places a legend on the plot. 74) Block execution of the GUI. 77) Get the current frame.(p. 66) Adds the text at a particular location. 66) Plots the speciﬁed function within the limits given. 74) Create a user interface component.(p. 66) Creates a new graphics window and makes it the current target.(p. 66) Returns the current value of the property of an object. 58) Places the text at the point given by the mouse. 77) Save a ﬁgure to disk.(p. 77) Save the current movie frames to an avi ﬁle.

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

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

quadl

161

(p. 148) Matrix logarithm. 148) Matrix square root.(p. 137) Calculates the derivative of a polynomial.(p.(p.(p.(p. 137) Calculates the integral of a polynomial. 137) interpolates a piecewise polynomial calculated by pchip or spline. 148) 162 .(p. (p.(p.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.(p. 137) Calculates the coeﬃcients of a polynomial given its roots.(p.(p. 137) Calculates the least-squares polynomial of a given degree which ﬁts the given data. 137) Does three-dimensional interpolation. 137) Does two-dimensional interpolation.(p. 137) Evaluates a polynomial at a point. 137) Cubic spline interpolation. 148) Evaluate general matrix function.(p. 137) Numerically calculates all the zeroes of a polynomial.(p. 137) Evaluates a polynomial with a matrix argument. 137) Cubic Hermite interpolation.(p. 137) Matrix Functions expm funm logm sqrtm Matrix exponentiation.

5 % or C = sqrt(A) A A % or mean(R(:)) b) ˆ ˆ B 2 ˆ C.1a) > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > A = [1 2 3 4.1). 2. 7 8 10] B = A .tril(A.6850e+06i ˆ ˆ > > th = input( th = ). 1 ) .7a) ˆ A = [ ones(6.3637e+07 . 2) .10) = -5 A = A .3) 2. 5:8.7.2*a*b*cosd(ab)) > > format long > > c answer: 6.6.2) 1. 9 10 11 12. 2 ˆ % or x = [0:30].:) + A(3.9.10.7.9.3) > > diary triangle. c = sqrt(a 2 + b 2 . cos(2*th) .175085147187636 > > > > or > > asind( (b/c)*sind(ab) ) answer: 4.10. and 4. .10. 2.ans > > (1.2) 2. 13 14 15 16] A = [1:4. 1 ) .1i*12 20) (1/3) answer: 1.Solutions To Exercises These are the solutions to the exercises given in subsections 1.1a) or > > answer: b) > > > > a = 3. A(6.10. 13:16] A = [ [1:4:13] [2:4:14] [3:4:15] [4:4:16] ] A(2. ab = 79.2e20 .1) ˆ 1. im] = max(R ) mean(mean(R)) S = sin(R) r = diag(R) A = [1 2 3. 3.5 % or B = sqrtm(A) C = A.10.4) zeros(6) ].:) A = 4*eye(n) .4) help fix or doc fix.6a) b) c) d) e) 2.diag( ones(n-1.9.diag( ones(n-1.7.diag( ones(n-1.:) = (-9/5)*A(2.(2*cos(th) 2 . 1. 5 6 7 8. deg = pi/180.10.diag( exp([2:n]).4a) b) 2.5) 2. 4 5 6. A(1.1751 ˆ b 2 ˆ . -1 ) b) 2. 2 ˆ R = rand(5) [m.1) = 5.1).9448e+01 format short e asin( (b/c)*sin(ab*deg) ) / deg c) d) 1.9.9.-1) x = [0:30] .2*a*b*cos(ab*deg)) + ˆ c = sqrt(a 2 ˆ 6.10. 2 ˆ 163 . b = 5.1).10.7. 9:12. -1 ) A = diag([1:n].

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

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

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. Dot / Forward slash 0 1 2 3 4 5 6 7 8 9 : Colon . Comma Minus sign or dash . 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 .

ˆ 168 . 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. 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 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.

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

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

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

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

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

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

Erase (a .

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

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

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

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

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

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

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

Index 182 .

Sign up to vote on this title

UsefulNot useful- matlab
- Matlab
- matlab
- learnmatlab_sp3
- matlab70
- The Mathworks_matlab Oop
- (eBook) - Matlab - Engineering Problem Solving
- matlab
- matlab
- Vedic Mathematics
- Business Economic and Managerial Decision Making
- Stochastic Programming
- Stochastic Programming
- Polya and Szego - Problems and Theorems in Mathematical Analysis 2
- Hoffman, Kunze. Linear Algebra (2ed, PH, 1971)(T)(415s).
- CalcII Complete
- Data Structures
- Mathematics of Evolution
- Quantitative Methods
- Barr, Category Theory
- CalcIII Complete
- Geographic Information Systems in Transportation Research
- Timeless Decision Theory
- Stochastic Analysis - Classical And Quantum - T. Hida (World, 2005) WW
- Data Structures
- 9491216465StochasticGames
- Data Structures
- Transformation Groups
- matlab

Are you sure?

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

We've moved you to where you read on your other device.

Get the full title to continue

Get the full title to continue reading from where you left off, or restart the preview.

scribd