## Are you sure?

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

3:32 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 22 27 30 31 33 33 36 37 38 39 40 41 42 45 47 48 48 57 60 65 67 73 76 76 77 80 81 82 84

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

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

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

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

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

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

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

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

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

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

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

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

90 90 95 99 111 112 115 118 118 123 129 133 136 138 145 147 147 147 148 148 148 149 150 150 151 151 151 152 152 153 153 154 154 155 155 156 156 156 157 157 157 158 158 158 159 159 159 161 165 167

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

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

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

• you can use the left-arrow key.e. click on a MATLAB icon or type matlab in a terminal and wait for the prompt. . If you do not specify a ﬁle. For example..) You are now in the MATLAB workspace. the ﬁle is not overwritten). 5i can be input as 5i or as 5*i.e.17*5.. . to move backward. while 5×1030 i can be input as 5e30i or as 5e30*i or as 5*10 30*i.1. Conversely.. this can get very time-consuming. i. but must be input as 1e-20 or 1E-20 or 1. you will want to reexecute the previous line. enter >> (2 + 2i) 4 and MATLAB returns −64. if you are involved in a continuing project.7 + 17/3 by entering >> 3.e-20 or 1. i. “ ←”. .1. You can later use an editor to extract the part you want to turn in. You can also save all of your input to MATLAB and most of the output (plots are not saved) by using the diary command. “ ↑”. √ MATLAB can also handle complex numbers.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. you might have made a mistake in the previous line and so it did not execute. where i or j represents −1 . You can calculate 3. 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. i.E-20 or . this archive is saved to the ﬁle diary (no extension) in the present directory. i. this is appended to the end of the ﬁle (i. ↓” to move forward). To calculate (2 + 2i)4 .e. one statement at a time (or the down-arrow key. Of course.e.e. For example. or did not execute correctly. Then hit the enter (or the return) key to execute the line. Scalar Calculations 1. Frequently.0000e-20 The “standard” way to input 2×10−20 is as 2e-20 or 2E-20 or 2. Instead. If the ﬁle already exists. Because of this feature you can use the diary command without fear that crucial work will be overwritten. ˆ ˆ ˆ ˆ ˆ ˆ ˆ 6 . and the right-arrow key. or another previous line. (To exit MATLAB. if it is very long. For example.. This archive of your work can be invaluable when you are solving homework problems. or • you can use the mouse to move back and forth in the line. “ →”. Warning: 10−20 cannot be input as e-20. to appear. Simple Arithmetical Operations MATLAB can be used as a scientiﬁc calculator. while “burying” all the false starts and typing mistakes that occur. If you are entering a line and make a mistake. i. To begin a MATLAB session. but not as 5*10 30i (which MATLAB considers to be 5×1030i ). uses “e” to represent “10 ” so that MATLAB displays 2.e. > click on Exit MATLAB in the File menu item or type exit or quit. to move back and forth in the line. “ > ”.e-20 or 2..17 · 5. however. you can enter 2×10−20 by >> 2*10 -20 MATLAB. this archive can be invaluable in keeping a record of your progress.E-20 (even 2.0000000e-00020 is acceptable). you can use the up-arrow key. you can just retype the line — but..

1) and obtain the same result.17*x 3 + 79. MATLAB also contains some predeﬁned variables. one line at a time.2. Nothing will be printed out because semicolons follow each command.1.17*x 3 + 79 There can also be more than one command on a line. just as in a programming language. If you want everything printed out then type >> x = 2 (1/3). No warning messages are printed if a variable is overwritten. For example.e. it is saved to the ﬁle diary in the current directory. Many of these are contained in the ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ ˆ 7 . Character strings can also be stored in variables. then all three commands will be executed. g = 3/fx. Exponentiation (i. use two single quote marks. Variables can be used to store numerical values. Left division. g = 3/fx Thus. But you can also type >> fx(1) or >> fx(1. At start-up time. For example. the results appear on the computer screen. For example. ˆ diary Saves your input to MATLAB and most of the output to disk. Warning: A variable can be overwritten at will. The up-arrow key moves backward in the MATLAB workspace. If you now type > > x = x + 5 then x becomes 21/3 + 5. if you type >> x = 2 (1/3).. Unlike C. Variables Arithmetical Operations a+b a-b a*b Addition. Multiplication. at present x = 21/3 . 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 . For example. for example. the results of the statement are not displayed. and its type depends on its context. you can separate statements on a line by commas or semicolons. A variable springs into existence the ﬁrst time it is assigned a value. fx = 3*x 6 . ↑ 1. ab ). If semicolons are used. This command toggles diary on and oﬀ. (If no ﬁle is given. 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. it is important to understand that MATLAB considers scalar variables to be vectors of length one or matrices of size 1×1. Subtraction. Variables Notation: We always use lowercase letters to denote scalar variables.) diary on turns the diary on. to store the string “And now for something completely diﬀerent” in a variable. fx = 3*x 6 . (this is exactly the same as b/a ). enter >> str = And now for something completely different (We discuss text variables in more detail in Section 3. diary <file name> saves to the named ﬁle.17*x 3 + 79. diary off turns the diary oﬀ.2. Although we do not discuss vectors and matrices until the next section. if you type >> fx the number 57 is returned. For example. but if commas are used. variables do not need to be declared (or typed). a/b a\b a b Division.) Note: To put a single quote mark into the string.

Variables table below. This is done by using disp. Warning: Be careful since you can redeﬁne these predeﬁned variables. The reserved words.6 then >> x returns ˆ x = -23.) Variables can also be deleted by using clear.5/3. which will be discussed in Section 6.5 − 5/3.1) 2 but then realize that you wanted to save this value. 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.1)2 . it does not. called keywords. Incidentally. For example.) displays -23. For now. digits. However. Probably the most useful of these is pi.1.5 . and underscores where the ﬁrst character must be a letter. For example. are break case catch classdef continue else elseif end for function global if otherwise parfor persistent return spmd switch try while (Of course. simply enter >> x = ans and x now contains (3. there are a few names which are reserved because they have special meanings. if you type >> (3. which contains the last calculated value which was not stored in a variable.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. 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.2 · 17.2. it sometimes happens that you forget to put a value into a variable. The maximum length of a name is too long to worry about. For example. We will discuss character strings in detail in Section 3. For example.3. if x has the value −23.2*17. but instead you type 8 . allows much ﬁner formatting of variables. you can still use End or END — but you probably shouldn’t. it follows with a blank line. >> disp(x) >> disp(pi 3) >> disp( And now for something completely different ) >> disp( -----------------------------------------. For example. when it displays a string or a string variable.) Note: When disp displays a variable or an array or an expression. Then MATLAB sets the expression equal to the variable ans. a valid name for a MATLAB variable is a character string containing letters (upper or lower case). However. In MATLAB it is trivial to display a variable: simply type it.0063 And now for something completely different -----------------------------------------(The command fprintf.6000 ˆ 31. >> x = Silly Walks puts the text “Silly walks” into the variable x. For example.

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

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

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

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

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

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

1.8. Help!

Warning: The ﬁle name can consist of (almost any number of) letters (lowercase and/or uppercase), numbers, and underscores, i.e. “ ”.

Warning: There is one point we cannot overemphasize.

Make sure your

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

The

rst character must be a letter. Spaces are not allowed.

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.) To check this, you can enter > > type <file name> before you save your m-ﬁle. 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. If the ﬁle name doesn’t exist, MATLAB returns ??? Undefined function or variable <file name> . If MATLAB returns your m-ﬁle, it means you have already saved it. In this case enter > > doc <file name> (which is discussed in the next section), which returns useful information about a MATLAB function, i.e., not one of yours. If it cannot ﬁnd this particular function, you are safe. A long expression can be continued to a new line by typing three periods followed by the “enter (or 20 “return”) key. For example, j=1 1/j can be entered as >> 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9 + 1/10 + 1/11 + 1/12 + ... 1/13 + 1/14 + 1/15 + 1/16 + 1/17 + 1/18 + 1/19 + 1/20 although there are much better ways to obtain this same expression with many fewer keystrokes (as you will see in Section 2.8). Lines can also be continued in the MATLAB workspace by using three periods, but it is much more common to use continuation in an m-ﬁle. If your m-ﬁle is very long, it is often valuable to include comments to explain what you are doing. Each line of comments must begin with the percent character, i.e., “%”. Comments can appear alone on a line or they can follow a statement that you have entered. Odds and Ends edit type ... % Create a new m-ﬁle or edit an already existing one. Displays the actual MATLAB code for a command or function or m-ﬁle. Continue an expression onto the next line. Begin a comment

1.8.

Help!

Before discussing how to obtain help in MATLAB, here is a good place to discuss a very frustrating situation where you desperately need help: how do you abort a MATLAB statement which is presently executing. The answer is simply to type C (that is, hold down the control key and type “c”). The on-line help facility in MATLAB is quite extensive. If you type >> help you will get a list of all the topics that you can peruse further by typing help followed by the name of the topic. If you want help on a speciﬁc command, simply type help followed by the name of the command, i.e., >> help <command> For example, if you forget the exact form of the format command, just type >> help format and you will see all the various ways that the output can be formatted. Note: Typing

ˆ

15

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

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

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

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

.e. 47... n. You can also generate the identity matrix. 49. x(length(x)) = x(length(x)) + 1 where length returns the number of elements in a vector. Similarly. every time that this command is executed during a session. . For example. i. a diﬀerent sequence of random numbers is generated.. (Presumably the “nonrecommended” procedure will still be usable for many years.e. If A (see the beginning of this section) has already been generated. such as A. . >> C = zeros(5) or >> C = zeros(5. 48. not the seed. . This is generated by the rand command. the element xi of the vector x is x(i) in MATLAB. MATLAB also has a number of commands that can generate matrices. The command randn generates a random matrix where the elements are normally distributed (i. Gaussian distributed) random numbers with mean 0 and standard deviation 1. Seed . The command randperm(n) generates a random permutation of the integers 1. 51)T ∈ R50 enter >> x = [1:50] . B(3.1. 2. [.). <non-negative integer state number>) Note: This procedure for generating an initial seed is no longer recommended.) Random matrices are often useful in just “playing around” or “trying out” some idea or checking out some algorithm. There is another “random” function which is useful if you want to reorder a sequence. you are supposed to enter >> s = RandStream( swb2712 . >> C = zeros(5. the matrix with ones on the main diagonal and zeroes oﬀ of it. (. Suppose you want to create the matrix 1 2 3 B = 4 5 6 7 8 10 without having to enter all nine elements. and so the same sequence of random numbers will be generated. 20 . . You work with individual elements of a matrix by using round parentheses. 2. a matrix whose elements are all random numbers. For example. For example.]. by using the command eye with the same arguments as above. Also.. the simplest way is to type >> B = A. which takes the same arguments as above. i. Generating Matrices We have now discussed how to enter matrices into MATLAB by using square parentheses. n) or ones(size(D)). If desired.2. 1). 3. i. .j) in MATLAB. by >> C = zeros(size(A)) where size(A) is a row vector consisting of the number of rows and columns of A. However.3) = 10 Also. <non-negative integer state number>) >> RandStream. Instead.e.e. a diﬀerent seed can be set at any time by entering >> rand( state . 8) generates a 5×8 zero matrix. Every time that a new MATLAB session is started. the elements are uniformly distributed random numbers in the interval (0. 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.. x(50) = 51 or >> x = [1:50] . . that is. these are pseudorandom numbers because they are calculated by a deterministic formula which begins with an initial “seed” — which is called the state . you can generate a matrix with all ones by ones(n) or ones(m. to create the column vector x = (1. Finally. Speciﬁcally. Another useful matrix is a random matrix. . you can generate a zero matrix C with the same size as an already existing matrix. x(50) = x(50) + 1 or >> x = [1:50] . To be precise.setDefaultStream(s) which will make anyone who loves Java squeal with joy. . 5) generates a 5×5 zero matrix.. the element aij of the matrix A is A(i. the default seed is set..

. A Conjugate transpose. The arguments are the same as for zeros. The fact that the next entry is a column vector is immaterial.) This matrix could also be generated by >> [ A .e. the original matrices are submatrices of the ﬁnal matrix. Generates the identity matrix. This is easily generated by >> [ A . The size of a matrix. i. Generating Matrices Note: randperm changes the state of rand. That is. 9)T type >> [A [1 5 9] ] (The space following the A indicates that the next column is to follow. Generates a matrix whose elements are normally (i. i.n] = size(A) returns m and n as separate arguments. 21 . AT . [1 1 1] . . .. to put matrices together to make a larger matrix.. that is. The fact that A is a matrix in its own right is immaterial. n. 2. Generates a zero matrix with the same size as A. ones(1. All that is necessary is that the number of rows of A be the same as the number of rows in the new last column. [1 1 1] ] or even by >> [ A . For speciﬁcity.e. The initial seed is changed by rand( state .e.1) returns the number of rows (the ﬁrst element of A ) and size(A. Each time that this function is called during a session it returns diﬀerent random numbers. 3). All that is necessary is that the number of columns of A be the same as the number of columns of ones(2. ones(2. i. The arguments are the same as for zeros. Generates a matrix whose elements are uniformly distributed random numbers in the interval (0. or [m. size(A. 3) . MATLAB also makes it convenient to assemble matrices in “pieces”. . The total number of elements in a vector or matrix. [1 1 1 . rand randn randperm(n) size(A) length(x) numel(A) A. to generate a 3×4 matrix whose ﬁrst three columns are the columns of A and whose last column is (1. <seed number>). the diagonal elements are 1 and the oﬀdiagonal elements are 0. AH . n) zeros(size(A)) ones eye Generates an n×n matrix with all elements being 0.2. The arguments are the same as for zeros. Generates an m×n matrix. Each time that this function is called during a session it returns diﬀerent random numbers. 3) ] (The semicolon indicates that a row has been completed and so the next rows consist of all ones. size(A) returns a two-vector of the number of rows and columns. Also. 1). 1 1 1] ] Similarly. The number of elements in a vector.1. . The arguments are the same as for zeros. Generates a matrix with all elements being 1.e. Gaussian) distributed random numbers with mean 0 and standard deviation 1. Transpose. let us continue with A (see the beginning of this section). ones(1. Suppose you want a 5×3 matrix whose ﬁrst three rows are the rows of A and whose last two rows are all ones.2) returns the number of columns (the second element of A ). Generates a random permutation of the integers 1.) Elementary Matrices zeros(n) zeros(m. 5.. 3) ] or by >> [ A .

3). .979.98. . An easy “ﬁx” to avoid this possibility is to calculate x by > > x = [20:980] /1000 2. a + 1. The Colon Operator For real numbers a and b the MATLAB command >> [a:b] or. 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. This possiblity is much more real in the programming language C.4π. MATLAB will not complain. . .98] should generate the column vector (0. 5. the vector x = (1. we can generate numbers in any arithmetic progression using the colon operator.3. . 0. 9. 15.98)T . You can use the colon notation to extract submatrices from E. . .02 : .9] (although we can’t imagine why you would want to do it this way). entering > > x = [. 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 .02. while typing >> [ pi : -. the condition i <= 0. 2. 0. 4.001 ) generates successive values of i by adding 0.2*pi : 0 ] generates the row vector (π. a + k) where the integer k satisﬁes a + k ≤ b and a + (k + 1) > b. typing >> [18:-3:2] generates the row vector (18. it will simply return “ []” which is an empty matrix.001 to the preceding value. . i <= 0. there is a possibility that the last element in x will be 0. For example. However. the statement for ( i = 0. i = i + . 22 23 24 28 29 30 which can be generated by >> E = [ 1:6 .8π.2.3.6π.1. more simply.98 will be false and the loop will not be evaluated when i should be 0. a + 2. 0.022. . For example. Thus. It is possible that when i should have the value 0.02.† We will discuss the command linspace which avoids this diﬃculty in Section 4. because of round-oﬀ errors in storing ﬂoating-point numbers. Manipulating Matrices 2. 25:30 ] Note: Spaces will frequently be used in MATLAB commands in this subsection for readability.2. 6)T should be entered into MATLAB as >> x = [1:6] or even as >> x = [1:6. 0. but it still remains. . The MATLAB package was written speciﬁcally to minimize such a possibility. As an oversimpliﬁed example. 7:12 .2π.98. . 19:24 .021.979. 3. due to round-oﬀ errors the value will be slightly larger. For example. Thus.001 : .98. 13:18 . 12. † 22 . Warning: There is a slight danger if c is not an integer. . 6. >> a:b generates the row vector (a. Occasionally your ﬁngers will go crazy and you will type something like >> [10:1] (rather than [1:10] ). 0).

enter the single line >> G([5 3]. A diﬀerent command is needed to work on the diagonals of a matrix. On the left side of an equation. as we did above. -2) 23 .:) >> G(5. 30)T ).2) . 23. E(:) is a column vector with the elements being the columns of E in order. 8. for. 6:-1:1 ) generates a matrix with the same size as E but with the columns reversed. [2 3 4 5] ) extracts the elements in the ﬁrst. 26 27 28 29 You can generate this submatrix more easily by typing >> F = E( 1:2:5 . and more transparent. thus. third. to switch the third and ﬁfth rows of G. [2:end] ) The keyword end designates the last element of the dimension: 5 for the rows of E and 6 for the columns. or switch (as we will see later). third.2. the next ﬁve elements of f are the second column of E. Finally. 24 23 22 21 20 19 30 29 28 27 26 25 It is also very easy to switch rows in a matrix. This is not a very useful way of entering E. while. 15. Simply type >> F(:.:) = G(5. we will not discuss this reshaping further because the reshape command described below is easier to understand. Note: On the right side of an equation.3:4) There is a last-additional shortcut you can use. For example.:) = G([3 5].e. and it must terminate a nested function (as we will also see later). For example.). This can be easily done by >> F = E( [1:2:end] .:) prints out exactly the same matrix as entering E (as does E(1:end. 1) (so d1 is the column vector (2. Note: The keyword end has a number of meanings. 9. it can also terminate a primary function or a subfunction.e. but it shows how the colon operator can work. and ﬁfth columns of E.:) >> G(3. fourth. than the three lines >> temp = G(3.. the second column of F is F(:. It also ends a block of code begun with a if. 6 5 4 3 2 1 12 11 10 9 8 7 G = 18 17 16 15 14 13 . i. etc. Manipulating Matrices >> F = E( [1 3 5] . However.. there is one more use of a colon. one above the main diagonal by typing >> d1 = diag(E.:).4*F(:. To replace the second column of F by two times the present second column minus four times the fourth column enter >> F(:.2) = 2*F(:.2) and the second row is F(2. and ﬁfth rows and the second. For example. entering E(:. 2:5 ) There is an additional shortcut you can use: in a matrix a colon by itself represents an entire row or column. 22.:) = temp Finally. E(:) reshapes a matrix. 29)T ). entering >> G = E( : .4) And suppose you now want to double all the elements in the last two columns of F. you extract the main diagonal of E by typing >> d = diag(E) (so d is the column vector (1. 16. and two below the main diagonal by typing >> d2 = diag(E. On the other hand. You might be changing the size of E and not want to have to remember how large it is. 2 3 4 5 F = 14 15 16 17 . Suppose you want the matrix F to consist of the odd rows of E and the second to the last column. the ﬁrst ﬁve elements of f are the ﬁrst column of E.:) which is much simpler.3. The colon operator works on rows and/or columns of a matrix. Returning to “ :”.3:4) = 2*F(:. Entering >> f = E(:) generates a column vector consisting of the columns of E (i.1:end) ).

2.3. Manipulating Matrices

(so d2 is the column vector (13, 20, 27)T ). The MATLAB function diag transforms a matrix (i.e., a non-vector) into a column vector. The converse also holds: when diag is applied to a vector, it generates a symmetric matrix. The command >> F = diag(d) generates a 5×5 matrix whose main diagonal elements are the elements of d, i.e., 1, 8, 15, 22, 29, and whose oﬀ-diagonal elements are zero. Similarly, entering >> F1 = diag(d1, 1) generates a 6×6 matrix whose ﬁrst diagonal elements (i.e., one above the main diagonal) are the elements of d1, i.e., 2, 9, 16, 23, 30, and whose other elements are zero, that is, 0 0 0 F1 = 0 0 0 2 0 0 0 0 0 0 9 0 0 0 0 0 0 16 0 0 0 0 0 0 23 0 0 0 0 0 . 0 30 0

Finally, typing >> F2 = diag(d2, -2) generates a 5×5 matrix whose −2nd diagonal elements (i.e., two below the main diagonal) are the elements of d2, i.e., 13, 20, 27, and whose other elements are zero, i.e., 0 0 F2 = 13 0 0 0 0 0 20 0 0 0 0 0 0 0 0 0 27 0 0 0 0 . 0 0

The Toeplitz matrix is a very special matrix whose values are constant along each diagonal. For example, 7 4 3 1 4 3 −2 7 −5 −2 7 4 −1 −5 −2 7 is generated by toeplitz([7 -2 -5 1], [7 4 3 1]) If the Topelitz matrix is symmetric, only the row or the column elements need be entered (i.e., only one argument is required). You can also extract the upper triangular or the lower triangular part of a matrix. For example, >> G1 = triu(E) constructs a matrix which is the same size as E and which contains the same elements as E on and above the main diagonal; the other elements of G1 are zero. This command can also be applied to any of the diagonals of a matrix. For example, >> G2 = triu(E, 1) constructs a matrix which is the same size as E and which contains the same elements as E on and above the ﬁrst diagonal, i.e., 0 2 3 4 5 6 0 0 9 10 11 12 G2 = 0 0 0 16 17 18 . 0 0 0 0 23 24 0 0 0 0 0 30 The similar command tril extracts the lower triangular part of a matrix. As an example of the relationship between these three commands, consider the square random matrix F generated by 24

2.3. Manipulating Matrices

>> F = rand(6) All the following MATLAB commands calculate F anew: >> triu(F) + tril(F) - diag(diag(F)) >> triu(F, 1) + diag(diag(F)) + tril(F, -1) >> triu(F) + tril(F, -1) >> triu(F, 2) + diag(diag(F, 1), 1) + tril(F) Note: Numerically the ﬁrst command might not generate exactly the same matrix as the following three because of round-oﬀ errors. It is important to note that diag , triu and tril cannot appear on the left-hand side of an equation. Instead, to zero out all the diagonals above the main diagonal of F enter >> F = F - triu(F, 1) and to zero out just the ﬁrst diagonal above the main diagonal enter >> F = F - tril(triu(F, 1), 1) What if you want to insert numbers from the upper right-hand corner of a matrix to the lower left-hand corner? There is no explicit function which does this but there are a number of indirect functions: fliplr(A) ﬂips the matrix from left to right, i.e., reverses the columns of the matrix; flipud(A) ﬂips the matrix up and down, i.e., reverses the rows of the matrix; rot90(A) rot90 rotates the matrix 90◦ ; and rot90(A,k) rotates the matrix k×90◦ . MATLAB has a command which is useful in changing the shape of a matrix while keeping the same numerical values. The statement >> K = reshape(H, m, 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). A column vector is generated from H, as in H(:), and the elements of K are taken columnwise from this vector. That is, the ﬁrst m elements of this column vector go in the ﬁrst column of K, the second m elements go in the second column, etc. For example, the matrix E which has been used throughout this subsection can be easily (and quickly) generated by >> E = reshape([1:30], 6, 5) Occasionally, there is a need to delete elements of a vector or rows or columns of a matrix. This is easily done by using the null matrix []. For example, entering >> x = [1 2 3 4] >> x(2) = [] results in x = (1, 3, 4)T . As another example, you can delete the even columns of G by >> G( : , 2:2:6 ) = [] The result is 6 4 2 12 10 8 G = 18 16 14 . 24 22 20 30 28 26 Also, occasionally, there is a need to replicate or tile a matrix to form a larger matrix. The command >> B = repmat(A, m, n) generates a matrix B which contains m rows and n columns of copies of A. (If n = m then repmat(A, m) is suﬃcient.) If A is a p by q matrix, then B ∈ Rmp×nq . This even works if A is a scalar, in which case this is the same as >> B = A*ones(m, n) (but it is much faster if m and n are large since no multiplication is involved). One frequent use of repmat is when a speciﬁc operation is to be applied to each row or to each column of a matrix. For example, suppose that the column vectors { x1 , x2 , . . . , xn } have been combined into the matrix X and we want to calculate the corresponding matrix for the vectors yj = xj + a for all j ∈ N[1, n]. This can be easily done by >> Y = X + repmat(a, 1, n); which, unfortunately, requires that the new matrix A = repmat(a, 1, n) be created. We would prefer to 25

2.3. Manipulating Matrices

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

26

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

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

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

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

2.6. 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 ( ,, ) . ,, . ,, ,, + [unary plus] ,, [unary minus] ,, .∗ ,, ./ ,, .\ ,, ∗ ,, / ,, \ + [addition] ,, − [subtraction] : < ,, <= ,, > ,, >= ,, == ,, & | && ||

ˆ

ˆ

˜ ˜=

The unary plus and minus are the plus and minus signs in x = +1 and x = −1. The plus and minus signs for addition and subtraction are, for example, x = 5 + 1 and x = 10 − 13. Thus, 1:n+1 is 1:(n+1) because “ +” has higher precedence than “ :”.† Also, A*C\b = (A*C)\b because “ *” and “ \” have the same precedence and so the operations are evaluated from left to right.

2.6.

Be Careful!

Be very careful: occasionally you might misinterpret how MATLAB displays the elements of a vector or matrix. For example, the MATLAB command eig calculates the eigenvalues of a square

matrix. (We discuss eigenvalues in Section 7.) der 5, i.e., 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

,

(we discuss this matrix in detail in Section 5.2) enter >> format short >> eig(hilb(5)) MATLAB displays the eigenvalues as the column vector ans = 0.0000 0.0003 0.0114 0.2085 1.5671 You might think the the ﬁrst element of this vector is 0. However, if it was zero MATLAB would display 0 and not 0.0000. Entering >> format short e >> ans

On the other hand, in the statistical computer languages R and S (which are somewhat similar to MATLAB), “ :” has higher precedence than “ +” and so 1:n+1 is (1:n)+1 ≡ 2:(n+1).

†

31

2.6. Be Careful!

displays ans = 3.2879e-06 3.0590e-04 1.1407e-02 2.0853e-01 1.5671e+00 which makes it clear that the smallest eigenvalue is far from zero. On the other hand, if you enter >> format short >> A = [1 2 3; 4 5 6; 7 8 9] >> eig(A) MATLAB displays ans = 16.1168 -1.1168 -0.0000 It might appear from our previous discussion that the last eigenvalue is not zero, but is simply too small to appear in this format. However, entering >> format short e >> ans displays ans = 1.6117e+01 -1.1168e+00 -8.0463e-16 Since the last eigenvalue is close to eps, but all the numbers in the matrix A are of “reasonable size”, you can safely assume that this eigenvalue is zero analytically. It only appears to be nonzero when calculated by MATLAB because computers cannot add, subtract, multiply, or divide correctly! As another example of how you might misinterpret the display of a matrix, consider the Hilbert matrix of order two 1 1/2 . H= 1 /2 1/3 We write H100 as H100 ≈ 1010 while in MATLAB entering >> format short >> H = hilb(2) >> H 100 displays ans = 1.5437 0.8262 0.8262 0.4421 ,

ˆ

1.0e+10 * 1.5437 0.8262 0.8262 0.4421 It is very easy to miss the term “ 1.0e+10 *” because it stands apart from the elements of the matrix. Similarly, entering

32

2.8. Data Manipulation Commands

>> >> >>

format short H = hilb(2) ( H (1/2) ) 2 - H

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

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

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

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

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

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

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

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

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

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

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

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

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

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

hilb(5)) By the way. empty it using [].b = @cos.b(0) = 1. is a ﬁeld of a particular structure.c = @tan. vector . pi. structures can themselves be vectors or matrices. We can also use function handles in cell elements and structures.1). . @cot. @sec. >> fieldnames(Cs) returns ans = scalar text vector matrix and >> isfield(Cs. Tr. 44 . @cos. . or explicitly redeﬁne it by using the struct function. you have to either clear it using clear. For example. Cell Arrays and Structures Typing >> Cs returns Cs = scalar: 2. we can even store anonymous functions in cell arrays and structures. text .d = @cot. @tan. for example. 2+3i. Incidentally.4. matrix . you cannot change a nonstructure variable to a structure variable. @csc} so that T{2}(0) = 1. 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.e = @sec. For example.a = @sin. The ﬁeld names of a structure can be handled using the following two commands. Tr.. >> Cs(2) = struct( scalar . The command isfield determines if a particular name. Tr. ones(10. text .. They can be stored in a cell array by >> T = {@sin. Tr. matrix . Thus. For example. vector . suppose you want to work with all six basic trig functions.. which is stored in a string. Instead. They can also be stored in a structure by >> Tr. structures rule . Tr.(sf) = hilb(10 Warning: As with cells. vector ) returns 1. go cells . The command fieldnames returns a cell array containing all the ﬁeld names of a structure as strings.3. >> sf = matrix >> Cs. [1 2 3] . so that Tr.0000 + 3..f = @csc.0000i text: go cells vector: [3x1 double] matrix: [5x5 double] The structure can also be created using one command by >> Cs = struct( scalar .

logical: We will discuss logical variables in Section 8.5.e. < fieldname >= value. 45 . function handle: This provides a means to call a function indirectly. We will discuss some of these capabilities at the end of this subsection. Set one or more values of a structure 3. For completeness. For example. cell: A cell variable itself is an instance of the cell class. false. which can all be instances of diﬀerent classes. Remove one or more ﬁelds from a structure. i. Alternately. 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 > . ﬁrst we discuss the “fundamental” classes in MATLAB.e. Advanced Topic: Data Types and Classes >> C = {@sin. Order the ﬁelds of a structure to be in ASCII order.1. We have already described a number of fundamental classes. the variable x which is deﬁned by x = 1 is an instance of the double class. An important point to remember is that a variable in most programming languages is a single quantity. Advanced Topic: Data Types and Classes A MATLAB variable can have a large number of diﬀerent types of values.3. and we ﬁrst discuss those which occur frequently in this tutorial. 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). otherwise.. @(x) exp(sin(x)). Note: We cannot store function handles in standard matrices — we can only store numbers. char: All strings are instances of the char class. The OOP capabilities of MATLAB are similar to those in C++ and Java. which can all be instances of diﬀerent classes. we now list them all..5 and value 0. These values used to be called data types. i. if the corresponding element of A is > . not an integer class. Display all the contents of a cell array. However. @(x) exp(exp(sin(x)))} is allowed — but probably not very interesting. true. Create a structure with speciﬁed ﬁelds and values. double: By default any variable that is given a numerical value is a double precision ﬂoating-point number. each ﬁeld can be given a value by < struct > . a structure variable is an instance of the struct class.5. Get one or more values of a structure ﬁeld. Determine if input is a ﬁeld name of the structure. whereas in MATLAB it is a vector or a matrix or an array of quantities. each in the form of a matrix (from a 0×0 matrix up to an n dimensional matrix for any n ). MATLAB has 15 fundamental classes. Cells and Structures cell celldisp struct fieldnames getfield isfield orderfields rmfield setfield Preallocate a cell array of a speciﬁc size. but it can contain any number of elements. but it can contain any number of ﬁelds. struct: Similarly.5) Each element of C ∈ R2×2 has the logical value 1. Return all ﬁeld names of structure. These logical values are each 1 byte.

and aj = 127. to obtain an instance of the single class you can enter A = single(rand(5)) The same technique holds for all the numerical classes. A simple template for generating a new class is 46 .3. which is an instance of the int8 class. Warning: Caveat Emptor! The procedures for combining diﬀerent numerical classes is very diﬀerent from other programming languages. Continuing the previous example. use the function class. int8 ) returns 0.5 > > i = int32(3) > > j = int8(127) > > ai = a + i > > aj = a + j are ai = 9. >> class(i) returns int32 and >> isa(i. You can also determine if a variable has a particular class by using isa. Advanced Topic: Data Types and Classes 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. MATLAB has user-deﬁned classes. the results of > > a = 5. which is an instance of the int32 class. In addition. To determine the class of a variable. For example.5. similar to classes in object-oriented programming languages.

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

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

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

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

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

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

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

Of course. The command >> stairs(x. Two-Dimensional Graphics >> xmax = 4.000. The matrix is input by 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.. say to 100. y. y. which might be clearer. In this case.) The load command can also be used to read a matrix into MATLAB from a separate data ﬁle. These commands are discussed in detail in Section 6. additionally. This is done by >> errorbar(x. in the ﬁle name). >> M = csvread( <file name> ) reads in data from a ﬁle one row per line of input. y) which can also be considered to be the plot of a step function. Another way to calculate c. the vector y by using the plot command.4. u) Note: All the elements of l and u are non-negative. if any. (If desired. >> hist(x. The data must be stored in the data ﬁle one row per line. you can plot the curve connecting the data points along with the error bars by >> errorbar(x. l. e) Sometimes the error bars are not symmetric about the y values. Or you can enter 54 . and nrdata. The data can then be plotted as desired. >> nrdata = 1000. but it does not complete the rectangle. >> nrbin = 20. draws such a curve. nrbin).e. you need vectors l and u where at xi the error bars extend from yi − li to yi + ui . The diﬀerence between this command and csvread is that the numbers can be separated by commas or semicolons or by spaces. >> c = xmax*[ -1+1/nrbin : 2/nrbin : 1-1/nrbin ]. 1). xmax-xmax/nrbin. Data can also be entered into MATLAB from a separate data ﬁle. say to 100. The command csvwrite writes the elements of a matrix into a ﬁle using the same format. you have an error bar of size ei for each point yi . If. is >> c = linspace(-xmax+xmax/nrbin. A stairstep graph is similar in that it draws the continuous curve describing the maximum of the histogram. We have already seen how to plot the vector x vs. For example.1. A histogram shows a graphical image of discrete data by stacking rectangles next to each other. If you now rerun this code you will see a much smoother histogram. to get a “good” histogram you should increase nrbin. >> x = randn(nrdata. c) Note that c contains the midpoints of each bin and not their endpoints. The numbers in each line must be separated by commas. which are similar to their C counterparts. you can have much more control over how data is input and output by using the fscanf and fprintf commands. drop the extension.

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

Reads data into MATLAB from the named ﬁle. print -deps <file name> saves the plot in the ﬁle using encapsulated PostScript (so it can be plotted on a PostScript laser printer). Prints a plot or saves it in a ﬁle using various printer speciﬁc formats. For example. importdata( <file name> ) csvwrite( <file name> . the numbers in each line must be separated by commas.4.1. A) print 56 . Two-Dimensional Graphics Input-Output csvread( <file name> ) load( <file name> ) Reads data into MATLAB from the named ﬁle. one row per line of input. one row per line of input. the numbers in each line can be separated by spaces or commas. Writes out the elements of a matrix to the named ﬁle using the same format as csvread. Similar to load but there need not be the same number of elements in each row. The name of the resulting matrix is <file name>.

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

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

61). th) ( r + exp(2*r. Th] = meshgrid(r. Z] = ndgrid(x. z). >> [X.4. Y= 1 2 3 6 6 6 1 2 3 7 7 7 while >> [X. 4:7) returns 1 X = 2 3 1 2 3 1 2 3 1 4 2 . Y] = meshgrid(1:3. 1. The diﬀerence between the two functions is that the order of the ﬁrst two arguments is reversed. It can also generate a grid in three dimensions by. or contour.*sin(2*th)) ) . mesh.2 − r cos 3θ for r ≤ 1 f (r. Y = 4 3 4 5 5 5 6 6 6 7 7 7 59 . >> x = linspace(-3. ezmesh. Y. 11) . 4:7) returns 1 2 3 4 4 4 1 2 3 5 5 5 X= .*cos(3*th) ). Three dimensions is the hightest we can go with meshgrid. y. Three-Dimensional Graphics ezcontour. the code which plots r + e2r sin 2θ 1. 2. 1. 41) ./ ( 1. >> r = linspace(0. and ndgrid can be used in any number of dimensions. ezcontour3. 51). >> surf(X. a multidimensional grid can also be generated by >> [X. θ) = is >> f = @(r. y. For example. >> th = linspace(0. >> [R. 2*pi. Y] = pol2cart(Th. A surface can also be plotted in polar coordinates. Y. z). Y. For example. Th)) The function pol2cart transforms the polar coordinates into cartesian coordinates which can be understood by surf. We close with an additional detail about meshgrid. >> y = linspace(-2. f(R. However. Y] = ndgrid(1:3.2. for example. th). >> z = linspace(0. 61) .r. >> [X. and ezsurf. 3. Z] = meshgrid(x. >> [X. R).2 .

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

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

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

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

>> colormap(map). MATLAB can also plot a two-dimensional image (i. also in steps of 0.3 . max(F(:)) = 0. rather than elliptical. Fills one or more polygons with the color or colors speciﬁed by the vector or string <color>. j)th element of X speciﬁes the color to use in the current color map. <color>) fill3(x.e.) (In the demonstration program. thus a value of 0 corresponds to the middle row of C which is.89. The (i. the zero value of F has a value of (1. a picture) which is represented by a matrix X ∈ Rm×n . Plots a two-dimensional image. The ﬁlled contour is calculated in line 13.05. white.e. Then the row ic of C is calculated by ic = ﬁx (f mod − f min)(n − 1) f max − f min +1. Advanced Topic: Commands red.58. <color>) image 64 . (1 0 0). f max]) the value f is ﬁrst modiﬁed to lie in the interval [f min. f min]).. f max]). Then the image is displayed using the new color map. Determines the current color map or choose a new one. to the maximum value of F. Thus.e. >> colormap(map) The image command inputs the matrix X and the colormap map from clown. Fills one or more 3D polygons with the color or colors speciﬁed by the vector or string <color>. figure(n) makes the nth graphics window the current target. after clicking on “Visualization” double-click on “Image colormaps” to see the images which you can access in MATLAB and the existing color maps. clf colorbar colormap demo figure fill(x. Runs demonstrations of many of the capabilities of MATLAB..) Advanced Topic: Plots caxis([v min.3. the zero value of F does not correspond to white because the colors in the colormap change linearly from the minimum value of F. i. For caxis([f min. >> load earth >> image(X). Note: There is a linear scaling between the value of F and the corresponding color in the color map C ∈ Rn. The complete array C is calculated in line 11 and the colormap changed in line 12. in line 15 we attach the color map to the plot so that we can determine the values in the contour plot.4. (The axis command forces the earth to be round. 0.e. However. 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. i. Clear a ﬁgure (i.15. Values outside this interval map to the closest endpoint. in fact.. j)th rectilinear patch in the plot. Similarly. y. delete everything in the ﬁgure) Adds a color bar showing the correspondence between the value and the color.mat. 0. z. Finally. min(F(:)) = −0. f max] by f mod = max([min([f. Creates a new graphics window and makes it the current target.15). For example. 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. to display the color image of a clown enter >> load clown >> image(X). i. y. This color appear in the (i... >> axis image displays an image of the earth.e.

. ypt. This is a collection of low-level graphics commands which do the actual work of generating graphics. >> set(h. <string>) gtext(<string>) legend(<string 1>. with handle h. a surface. red text which is rotated 90◦ . <Value 1>. . 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. and title. <Value 2>. such as a subplot. and a handle is the unique identiﬁer which refers to a particular object. 16. There are many properties of the text that can be changed in the text command by >> text(xpt. 90) results in a large. Places a legend on the plot using the strings as labels for each type of line used.4. In the former all the properties are set in the text command.) Obtains the current cursor position. Advanced Topic: Handles and Properties Advanced Topic: Text and Positioning ginput text(x. In handle graphics we consider every component of a graphical image to be an object.) We have shown two ways to customize the properties. (Each handle is a unique ﬂoating-point number. Of course. ypt.. xlabel. Instead. . Advanced Topic: Handles and Properties In this subsection we brieﬂy discuss handle graphics. (We show some names and values in the following table. a line. <string>) text(x. In the latter the text command creates an object. r . y. ) or >> h = text(xpt. ylabel.4. The low-level commands allow us to customize these graphical images. . using its default properties. we have to be able to refer to a particular object to change its properties. <Value 1>.4. Places the text at the point given by the mouse.. y. entering >> set(h. . <Prop 2> . zlabel. we will only discuss a few of — what we consider to be — the more useful customizations. a piece of text. Each object has properties and we customize an object by changing its properties. . For example. but at the cost of having to get much more involved in how graphical images are actually created. ) where <Prop ?> is the name of one of the properties for the text object and <Value ?> is one of the allowed values. z. FontSize . . Rotation . You can also change the default properties for gtext. etc. 65 . The set command then changes some of the properties of the object whose handle is h. <Prop 1> . <Value 2>.) We will use a small number of examples to explain handle graphics. Color . an axis. <Prop 1> . This subsection will be quite short because we do not want to get bogged down in this complicated subject. <string>. Adds the text to the location given in the units of the current plot. 4. The legend can be moved by using the mouse. <string>). <Prop 2> .

suppose we want to plot the function y = esin x for x ∈ [0. XTick . the fourth line puts the labels shown at each tick mark. [0 0 8. TickDir . (The default is 10 point. XMinorTick .5 inches high.) The font point size. This is frequently useful if subplot is being used to put a number of plots on a page. { 0 . We do this by >> x = linspace(0. . cap — The top of a capital letter is at the point. the graphical images do not ﬁll the entire page. blue. and green components.5*pi . XTickLabel . it is sometimes useful to put a title on the entire page.4. The name of the font to use.exp(sin(x))) >> set(gca. When a ﬁgure is printed. [0:pi/2:2*pi]) >> set(gca. (At present.5*pi . The property value is the angle in degrees. When we want to use the full size of a sheet of paper we use >> figure( PositionPaper . out ) where the third line puts major tick marks at multiples of π/2. [0 0 8. 1. Advanced Topic: Handles and Properties Text Properties Clipping on — (default) Any portion of the text that extends outside the axes rectangle is clipped off — No clipping is done. For a simple example which uses handle graphics. FontName ) and the string s now contains the name of the font. the ﬁfth line adds small tick marks between the labelled ticks. 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. baseline — The baseline of the text is placed at the point. 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. A three-element vector specifying a color in terms of its red. >> plot(x.5 inches wide and 5. For example. Color FontName FontSize HorizontalAlignment Rotation VerticalAlignment The more common way of customizing parameters is by using the set command. (The default is Helvetica. to get the font which is presenting being used enter >> s = get(h. 2*pi }) >> set(gca. The two arguments to get are the handle of the object desired and the name of the property. The two functions get and set are used to obtain the value of one parameter and to set one or more parameters. right — Text is right justiﬁed. we cannot use TEXcommands in XTickLabel to generate a Greek π.5 11]) since the default units for this property are inches.5 11]) or >> figure(n) >> set(gcf. or a string of the predeﬁned colors.) left — (default) Text is left-justiﬁed center — Text is centered. PositionPaper . center — (default) The text is centered vertically at the point.101). if subplot is being used. on ) >> set(gca. The text orientation. not just in 66 . and the last line puts the tick marks outside the plot boxed area. The default size is approximately 6.2*pi. top — The top of the text rectangle is at the point. 2π] and we want the horizontal axis to have major tick marks at every π/2 and we want these tick marks labelled. pi . bottom — The bottom of the text rectangle is placed at the point. Finally.4.) There is one case where we frequently use handle graphics.

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

the components.1*X + . b) n = 101. n).2η(y)]x2 + (b + 0. Thus..* Yxy. x = linspace(-2. bt = b + . view([-45. Y] = meshgrid(x. It is “rippling” in time (and the time is shown at the top of the 3D surface). we will show how to take a simple ﬁgure which is created by the plot command and add “something” to it. y = x. and the callbacks. and we will not discuss how to integrate your program and code the callbacks. Z). Instead. Since this can get quite complicated. 2.4*t. namely by writing all the actual commands which setup the ﬁgure.2*Yxy). Z = sin((at + . Read this documentation carefully and work through this explicit example yourself.2η(y)]η 2 (y) where η(y) = y + 0. 2 + . Yxy = Y + .25 sin 2(ex/2 − 1) .1x + 0. Y.01:10 at = a + . b) = sin [(a + 0.25*sin(2*(exp(X/2)-1)). This is well-documented in MATLAB. we will not attempt to describe all the commands which are involved in generating a GUI. Suppose we would like to stop the time evolution brieﬂy to admire the surface.2*Yxy). surf(X. including an explicit example which is called simple gui. but only a very small subset. 2)..4t)[sin 2η(y) + 0. bt*(sin(2*Yxy) + . [X. we only show two very simple examples.*X. a. t.4. We will not write any GUIs from scratch.5.8t) + 0. For the ﬁrst example consider the function function rippling(a. y. Advanced Topic: GUIs (Graphical User Interfaces) program. This is easily done by 68 . for t = 0:. 60]) xlabel( x ) ylabel( y ) zlabel( z ) title(t) drawnow end ˆ ˆ which generates the “interesting” surface z = f (x.8*t. y). We will not discuss guide any further. What we will discuss is how to use the non-simple way to write a GUI.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

you are still in the workspace so many MATLAB commands can still be executed. Execute the next executable line. For example. To terminate the “keyboard” session and return control to the m-ﬁle. you can examine any variables in the function’s workspace. If you have experience with using a debugger. Debugging Commands keyboard dbstep dbstep n dbstep in dbstep out dbcont dbstop dbclear dbup dbdown dbstack dbstatus dbtype dbquit return Turns debugging on. in function out = funct1(a. In particular. type >> echo on all The keyboard command is also very useful for debugging m-ﬁles. For example. Change the workspace to the calling function or the base workspace. However. (Alternatively. Change the workspace down to the called function. Executes the remainder of the current function and stops afterwards. t) 104 . this does not aﬀect function ﬁles. List the current function. Quit debugging mode and continue execution of the function. it returns complete control to the user to enter any and all MATLAB commands. since they are are used somewhat diﬀerently than in other programming languages. Execute the next n lines.3. you can run most MATLAB commands as long as you do not try to create new variables (but you can modify existing variables). enter K>> dbquit When using the debugger. Typing >> echo on turns on the echoing of statements in all script ﬁles (but not printing the results if the statements end with semicolons). However.8. There are two ways to run the debugger: you can type the debugger commands into the workspace. you are not running your program. To turn echoing on for a particular function. and echo off turns echoing oﬀ again. In addition. The only way you will recognize this is not a “standard” MATLAB session is that the prompt is K>> for Keyboard. especially when if statements are involved. because these are similar to commands in any debugger. Display all the calling functions. Remove a breakpoint. enter K>> return To terminate both the “keyboard” session and the execution of the m-ﬁle. type >> echo <function name> on and to turn echoing on for all functions. It stops execution of the m-ﬁle. The echo command is also useful for debugging script and function m-ﬁles. Quit debugging mode and terminate the function. you can also change the value of any of these variables. Thus. Function M-ﬁles pauses the code and also reminds you that it has been paused. Now we want to discuss the arguments in a MATLAB function. We will not discuss the commands in this debugger in detail.) Also. Instead. many of the commands you enter are commands for the debugger. Continue execution. or in a MATLAB window you can use the mouse and click on the commands. including the line numbers. The same as dbstep except that it will step into another m-ﬁle (rather than over it). Set a breakpoint. you can move the mouse over the variable name in the window and its description and value(s) will be shown. to distinguish these commands from “normal” MATLAB commands they begin with db. List all the breakpoints. similar to the pause command. doc will give you complete details. to see the values of variables just type the variable name into the workspace. you are running the debugger — and it is running your program. but only provide a brief description of each one. If desired.

(Note that a variable can be a local variable in one function and a global variable in another. Normally. >> x = WOW? >> x = x + 0 >> x = sum(x) >> x = x*[1 2. Note: The ﬁrst time you enter the function. In MATLAB. This is probably not something you should want to do frequently. there are three output arguments to funct2 and any of them can contain any type of variable.3. For example. In fact. 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. a persistent variable will be empty. (As we discussed earlier. For example. in MATLAB input arguments occur on the right side of the equal sign and output arguments occur on the left. In MATLAB it is done by declaring the variable persistent using >> persistent <variable 1> <variable 2> <variable 3> . it is frequently preferable to save the value of a local variable between calls to the function. If the workspace is also to share these variables. philosophy. Arguments which are to be modiﬁed by the function must occur on both sides of the equal sign in the calling statement. (This is true no matter what type of variables they are. not commas.) There is another diﬀerence between MATLAB and most other programming languages where the type of each variables has to be declared. Function M-ﬁles a and t are the input arguments and out is the output argument.. chemistry] = funct2([1 2 3]) >> [math. Sometimes it is very convenient to be able to “save” the value of a local variable so that it will still be in existence when the function is next called. In C. b. a single-precision ﬂoating-point number. out2. We now present a simple example where persistent variables are very helpful. then a scalar. a variable is a global variable if it appears in a global statement and a local variable if it does not. each of which can be any type of variable. 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. this may be desirable if a variable is modiﬁed by a function. as we discuss at the end of this section. and you can test for this by using isempty. there is no such requirement. a variable might be an integer. not commas. local variables come into existence when the function is called and disappear when the function ends. a double-precision ﬂoating-point number. the calling statement might be any of the following: >> art = funct2(1. must separate the variables in a global statement Instead of using a global variable. (There is an alternative to this awkward use of parameters which are modiﬁed by the function: you can make a variable global. 6. For example.) In C this is done by using global variables. this is not usually a good idea. However. out3] = funct2(z) z is the only input argument and there are three output arguments. on the other hand. There is no requirement that all three of these output arguments actually be used. MATLAB also has global variables which are deﬁned by declaring the variables to be global using >> global <variable 1> <variable 2> <variable 3> . i. Suppose we want to write 105 . c] = funct2(z) where z appears on both sides of the equal sign. either explicitly or implicitly. Warning: Spaces.) In function [out1.) This statement must appear in every function which is to share the variables. you must type this statement (or be put into a script ﬁle which you execute) before these variables are used. you can let the type of these arguments depend on the value or type of the input argument. and ﬁnally a matrix. For example. 3 4] It is particularly important to understand this “typelessness” when considering output arguments. [].5) >> [physics. a character string. That is. 5)) (just to be somewhat silly).. must separate the variables. etc. Occasionally. but it is sometimes very useful. horticulture] = funct2(reshape([1:30]. in funct2 if z is modiﬁed and returned in out1 then the calling sequence should be >> [z... For example.8. By the way.e. Warning: Spaces. then a vector. the following statements can follow one another in order and deﬁne x to be a string variable.. this is done by declaring the variable static.

beta. -y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ]. this function might be called repeatedly inside a general purpose function m-ﬁle. omega) and then afterwards call it as fncz4(y). or fncz3 might not be desirable — or even practical.alpha beta = param.5. Γ.0.. β. Later calls do not need to input these parameters because they have been saved in the function. and ω are parameters which will be set initially and then left unchanged during a run.) To make this last function easier to read we could write it as function z = fncz3(y. The second way is to use closure† . we will initially call the function as fncz4(y.) Now. Gamma.omega z = [ y(2) . 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. alpha. but they will be diﬀerent for each experiment. >> beta = 1. alpha.3. For instance. param) z = [ y(2) . We can always simplify this function by combining the four parameters into one structure by function z = fncz2(y.Gamma omega = param. In the initial call all the parameters are saved in persistent variables. alpha. fncz1 c(y) is evaluated as fncz1(y.beta Gamma = param. (If this function was more complicated it would be much harder to read.omega*t) ].05. beta. We do not want to “hardcode” the values in the function because we would have to repeatedly change the function — which is very undesirable. Gamma.8. -y(1)*(1-param.beta*y(1) 2)-param. omega) z = [ y(2) . We return to the function fncz1 and create a new function by >> alpha = 0.alpha*y(2)+. 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. which we have written. but then we have to include these four parameters in each call to the function. ˆ ˆ ˆ ˆ † A closure is a complicated term to explain. This discussion of saving parameters in functions has been somewhat lengthy — but it has many uses. (The parameter Gamma is capitalized even though it is not a matrix because γ is very diﬀerent from Γ. -y(1)*(1-beta*y(1) 2)-alpha*y(2)+Gamma*cos(omega*t) ]. 106 . alpha. Gamma. Another technical detail concerns how to “group” input arguments and/or output arguments together. alpha. >> Gamma = 0. many times for diﬀerent values of y.0.) We might be studying a mathematical model where this function will be evaluated many. end z = [ y(2) .Gamma*cos(param. Function M-ﬁles a function m-ﬁle to evaluate h(y) = y2 2 y1 (1 − βy1 ) − αy2 + Γ cos ωt where α. param. say general. >> fncz1 c = @(y) fncz1(y. omega). The ﬁrst way to reduce the number of parameters is to write the function m-ﬁle for h(y) as function z = fncz4(y. beta p = beta. fncz2. There are many reasons why evaluating h(y) using fncz1. omega p = omega. param) alpha = param. For each experiment these parameters will be ﬁxed. beta. beta. Gamma.. -y(1)*(1-beta p*y(1) 2)-alpha p*y(2)+Gamma p*cos(omega p*t) ]. Gamma p = Gamma. Certainly we can write the function as function z = fncz1(y. omega) (The “c” denotes the fact that duffing c is an anonymous function handle which is also a closure. omega) persistent alpha p beta p Gamma p omega p if nargin > 1 alpha p = alpha. but then it is harder to read the equation. >> omega = 1. Gamma. but we want to propose two other alternatives. beta.

They are placed following the primary function and between or following other subfunctions.e. we have nested functions. even if possible. Thus. NOT varargin(k). this block of code can be put into a new function and called from the original function.. Then we can declare the function as function fnc(varargin) or. The remedy is to split the code up into a number of functions.e. Warning: Recall that the k th argument in varargin is varargin{k}. Instead. the help. Sometimes these blocks can be combined by using a loop. Nested functions are more complicated than subfunctions and we will only provide a brief discussion. The only way to pass variables between these functions is through the argument list. and type commands can only access the primary ﬁle. First.. as function fnc x(x. diﬀerent m-ﬁles can contain subfunctions with the same name. They are similar to internal functions in Fortran 95. The ﬁrst function in the ﬁle is called the primary function and its name must agree with the name of the ﬁle. Function M-ﬁles especially when there can be a variable number of arguments.) Note: The primary function or a subfunction begins with the function deﬁnition line (i. function mﬁles can contain more than one function. Also. varargin) The varargin argument. 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 ). and it can be diﬃcult to debug the primary function.2 we code the function gravity using a number of nested functions. There are two further types of functions: Any remaining functions are called subfunctions or nested functions. In MATLAB functions normally have to be separated into diﬀerent ﬁles so that each function and its ﬁle name agree. the output argument varargout is handled exactly the same on the left hand side of the function declaration statement. When they are not suﬃcient. if a nested function is used then it — and all other functions — must end with the end statement. This can be annoying if a number of ﬁles have to be created: for example. x. the line which begins with the keyword function ). MATLAB cannot ﬁnd the function. However. The ﬁnal — but very important — technical detail about function m-ﬁles concerns an important element of programming style in any computer language. suppose there can be any number of input arguments to the function fnc. 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. subfunctions are suﬃcient — and they are much easier to describe.3. this often makes the code unwieldly. which are quite simple. otherwise. and they are somewhat related to inner classes in Java — but not in C++. but.† To make this discussion speciﬁc. then the call can be written as fnc2(varargin) By the way. (At the end of Section 10. This argument can even be passed into another function and will be handled exactly as if each element was passed separately. For example. if there is always at least the argument x. which must always be the last in the argument. For example. it can be diﬃcult to remember the purpose of all these functions. MATLAB has a feature to handle this proliferation of ﬁles. † 107 . is a cell vector whose length (which can be 0 ) is calculated by length(varargin). 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. It frequently happens that a block of code occurs two or more times in a function. It is possible to end the primary function and each subfunction with the command end. but this is not necessary because MATLAB recognizes that a function has ended when it encounters the next function statement. For example. consider the following function m-ﬁle. Usually. i.8. we discuss subfunctions. 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. if fnc x calls the function fnc2 and passes all but the ﬁrst argument. lookfor. each of which can be easily understood and debugged.

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

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

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

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

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

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

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

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

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

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. enter >> B = spdiags(S.. d.2 is not used since it would go into the element sn. but the size of the matrix will be adjusted. and the third column contains the corresponding values. whereas in the former case the vector which becomes the particular diagonal precisely ﬁts into the diagonal. if desired.)) Additionally. sparse and full matrices can be mixed together.3 of S1 contains the value 6. [1]. This data ﬁle should contain three columns: the ﬁrst two columns contain the row and column indices of the nonzero elements. For example. 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. since its value is zero. A slight variation of the above command is >> T = spdiags(B. (There is no equivalent command for non-sparse matrices so use full(sprandsym(. If this is not the size desired. The element s1. n) >> S = spdiags([0:-2:-2*n+2] .. It appears in the 3rd row of B because it occurs in the 3rd column of S1.9. you can generate sparse random symmetric matrices by sprandsym. n. n. a third way to generate the matrix S given above is >> S = spdiags([n:-1:1] . In addition. The type of the resulting matrix depends on the particular operation which is performed. 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. we can also extract the diagonals of a sparse matrix by using spdiags. There are a number of diﬀerent arguments for these functions. S) where T is equated to S and then the columns of B are placed in the diagonals of T speciﬁed by d. Then type >> S = spconvert(<sparsity matrix>) to generate the sparse matrix S. Use csvread or load to input the sparsity pattern from a data ﬁle into the matrix <sparsity matrix>. In addition. S) Just as with the diag command.) 117 . [0]. to extract the main diagonal of 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 matrix will also be positive deﬁnite. Thus. All of MATLAB’s intrinsic arithmetic and logical operations can be applied to sparse matrices as well as full ones. You can generate sparse random patrices by sprand and sparse. jA. although usually the result is a full matrix.n+1 . intrinsic MATLAB functions often preserve sparseness. normally distributed random matrices by sprandn.) The locations and values of the nonzero elements can be obtained by >> [iA. For example. (This element will not be used. Note that the size of S is determined from the maximum row and the maximum column given in <sparsity matrix>. one row in the data ﬁle should be “ m n 0” where the desired size of S is m×n. Note that the element bn. rho) Finally. sparse matrices can be input from a data ﬁle with the spconvert command.

Thus. Sparse uniformly distributed random symmetric matrix.1. 10. using MATLAB we can obtain a numerical approximation to the ode system d y = f(t. many more than in other sections of this overview. to provide a template of how to actually use the advanced features. The arguments are the same as for eye. Generates a sparse uniformly distributed symmetric random matrix. 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 118 . A) spy spconvert sprandsym Generates a sparse identity matrix. This ode has many diﬀerent types of behavior depending on the values of the parameters α. Converts a sparse matrix to a full matrix. 10. Applies the function to the nonzero elements of A. Instead.1. Generates a sparse matrix elementwise. Basic Commands Sparse Matrix Functions speye sprand sprandn sparse spdiags full find nnz spfun( <function name> . this is not in the form of a ﬁrst-order system. Generates a sparse matrix given the nonzero elements and their indices. Returns the number of nonzero elements in a matrix. Sparse normally distributed random matrix. which is called Duﬃng’s equation. However. the matrix can also be positive deﬁnite. Generates a sparse matrix by diagonals or extracts some diagonals of a sparse matrix. Finds the indices of the nonzero elements of a matrix. Plots the locations of the nonzero elements of a matrix. Initial-Value Ordinary Diﬀerential Equations Most initial-value ordinary diﬀerential equations cannot be solved analytically. As written. . We also provide a large number of examples. β. the commands become more involved if we want to explore the trajectories in more detail. The basic MATLAB commands are easily learned. and ω. Γ. 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. Basic Commands In this subsection we focus on the particular example y + αy − y(1 − βy 2 ) = Γ cos ωt .10. y) dt for t ≥ t0 where y ∈ Rn with initial condition y(t0 ) = y0 . the matrix can also be positive deﬁnite.

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

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

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

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

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

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

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

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

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

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

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

11. Boundary-Value Ordinary Diﬀerential Equations

where y ∈ Rn but conditions are given at both ends of the interval. If the boundary conditions are separated, then k conditions are given at x = a and n − k other conditions are given at x = b. If the boundary conditions are non-separated, then the conditions at x = a and at x = b are related. To allow any of these boundary conditions we write the boundary conditions as φ y(a), y(b) = 0 where φ ∈ Rn . For simplicity, we will only consider two closely related second-order odes, i.e., n = 2. This example should enable you to study any boundary-value ode. Consider the two nonlinear boundary-value ordinary 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, 1] where > 0. Our boundary conditions are φ y(0), y(1) = y(0) y(1) =0, (11.2) (11.1b) (11.1a)

which are called Dirichlet boundary conditions. These two odes are quite simple, but also quite interesting and challenging to solve for certain intervals in . We could use the Neumann boundary conditions y (0) = 4 and y (1) = −7 by φ y(0), y(1) = y (0) − 4 y (1) + 7 =0. (11.3)

Or we could use the mixed boundary conditions y(0) − y (0) = 1 and y(1) + 2y (1) = 3 by φ y(0), y(1) = y(0) − y (0) − 1 y(1) + 2y (1) − 3 =0. (11.4)

Finally, we could use periodic boundary conditions, which are non-separated, by φ y(0), y(1) = y(1) − y(0) y (1) − y (0) =0. (11.5)

The primary MATLAB function is bvp4c. However, the functions bvpinit and deval are also needed. We solve the boundary value problem by >> sol = bvp4c(<right-hand side>, <boundary conditions>, <initial guess>) There are two functions we need to write: odefun is f(x, y) and bcfun is the boundary conditions. For our example the ode given by function yp = nlode(x, y) global which ode eps if which ode == 1 yp = [y(2); -eps*exp(y(1))-2*y(2)]; else yp = [y(2); -(exp(y(1))+2*y(2))/eps]; end where we use global to input which ode to use and . The boundary condition is given by function bc = nlode bc(ya, yb) bc = [ya(1); yb(1)]; Since these boundary conditions are particularly simple, we also include the function function bc = nlode bc2(ya, yb) bc = [ya(1)-ya(2)-1; yb(1)+2*yb(2)-3]; for mixed boundary conditions (11.4). In addition, we have to choose an initial guess for y(x) using bvpinit by either >> bvpinit(x, y init) 130

11. Boundary-Value Ordinary Diﬀerential Equations

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

131

11. Boundary-Value Ordinary Diﬀerential Equations

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(p.(p. 57. 57) Generates an “easy” polar plot. (p. 57.(p. 60) Generates an “easy” contour in 3-D.(p.(p.(p. 57) Plots a step function. 57) Generates logarithmically spaced points. 60) Label contour lines. 57) Plots a curve through data points and also the error bar at each data point.(p. 60) Plots a ﬁlled contour. 57) Generates equally-spaced points.(p.(p. 57) Puts a title on the top of the plot.(p. 57) Updates the current ﬁgure.(p. 60) Generates an “easy” plot in 3-D. 60) Adds a color bar showing the correspondence between the value and the color.(p. 64) Raises the current graphics window so it is visible.(p. 57) 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. or an implicit function.(p.(p. 60) Controls the scaling and the appearance of the axes.(p. 64) The same as plot but the x axis is logarithmic. i.(p. 64) Determines the current color map or choose a new one. 57) The same as plot but the y axis is logarithmic.(p. 60) Fills one or more 3D polygons. 60) Raises the current graphics window so it is visible..(p.(p.(p. y(t) . 60) convert polar to cartesian coordinates. 60) Generates an “easy” 3-D surface using a wire mesh. 64) Plots a 3-D surface using a wire mesh. x(t). 60) Puts a label on the z-axis.(p.(p. y) = 0..Appendix: Reference Tables Two-Dimensional Graphics plot fill semilogx semilogy loglog ezplot polar ezpolar linspace logspace xlabel ylabel title axis hold hist hist errorbar subplot shg Plots the data points in Cartesian coordinates. i. 57) Divides the graphics window into rectangles and moves between them. 57) Plots a histogram.(p. 57) Puts a label on the x-axis.(p. 60) Changes the viewpoint of a 3-D surface plot.(p.(p.(p. 60) Plots a 3-D ﬁlled-in surface.(p.(p.(p.e. 60) Generates a 2-D grid.(p.e. 60) Generates an “easy” contour looking down the z axis. 57) Holds the current plot or release it. 60) Plots a contour in 3-D. 57) Plots the data points in polar coordinates.(p.(p. 60) Plots a contour looking down the z axis. 60) Generates an “easy” 3-D ﬁlled-in surface. 57) The same as plot but both axes are logarithmic.(p. 60) Divides the graphics window into rectangles and moves between them.(p. f (x.(p. 57) Generates an “easy” plot (similar to fplot ).(p. 60) Same as meshgrid except that the two arguments are reversed. It can also plot a parametric function. 57) Controls the scaling and the appearance of the axes.(p.(p.(p. 57) Fills one or more polygons.(p. similar to the colon operator. 57) 153 .(p. 57) Puts a label on the y-axis.

Cell Arrays.(p. 76) Save the current movie frames to an avi ﬁle. Structures.(p.(p. 42) Converts a string to a variable.(p. 73) Create a new avi ﬁle. 67) The current axes handle.(p. 73) Resume execution of the GUI. 73) Create a user interface component.(p.(p. 67) Sets the value of the property.(p.(p.(p.(p.(p..(p. 42) Compares strings.(p. 76) Add a frame to the avi ﬁle. 65) Obtains the current cursor position.(p. 42) Behaves very similarly to the C command in writing data to a text variable using any desired format.(p.(p.(p. 76) Close the ﬁle opened with avifile.(p. 64) Creates a new graphics window and makes it the current target. or properties of an object. 42) Behaves very similarly to the C command in reading data from a text variable using any desired format.(p.(p.(p. 45) Determine the class of a variable. delete everything in the ﬁgure(p. 45) Create a structure.(p.(p. 65) Returns the current value of the property of an object.(p. 76) Get the current frame. 47) 154 . 67) Invoke the GUI design environment to design your own GUI.(p. 45) Determine if input is a ﬁeld name.(p. 65) Adds the text at a particular location.(p.e. 47) Determine whether a variable is of a particular class.(p. 64) Runs demonstrations of many of the capabilities of MATLAB.(p.(p. 45) Return all ﬁeld names of a structure.Appendix: Reference Tables Advanced Graphics Features caxis clf demo figure fplot gtext image 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. 92) Preallocate a cell array of a speciﬁc size. 17. 73) Block execution of the GUI. 45) Display all the contents of a cell array. 65) Plots a two-dimensional image. 45) Set one or more values of a structure. 45) Remove one or more ﬁelds from a structure.(p. 45) Order the ﬁelds.(p.(p. 45) Get one or more values of a structure. 57) Places the text at the point given by the mouse. (p. 64) Clear a ﬁgure (i.(p. 76) Play movie frames.(p.(p. 76) Save a ﬁgure to disk. and Classes num2str sprintf sscanf str2num strcmp cell celldisp struct fieldnames getfield isfield orderfields rmfield setfield class isa Converts a variable to a string. 67) The current ﬁgure handle. 76) String Functions. 64) Places a legend on the plot.(p. 64) Plots the speciﬁed function within the limits given. 73) Create a user interface panel.(p.

57) Plots a histogram of the elements of a vector. 90) 155 .(p. 90) Calculates the pseudoinverse of a matrix. 82) Calculates the QR decomposition of a matrix. 36) The mean. positive deﬁnite matrix.(p. 90) Calculates the eigenvalues. 36) Plots a curve through data points and also the error bar at each data point. and eigenvectors if desired. 36) The standard deviation of the elements of a vector or each column of a matrix. or average.(p. 36) min mean norm prod sort std sum 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. 36) The sum of the elements of a vector or each column of a matrix. 79) Calculates the LU decomposition of a square invertible matrix.(p. 90) Calculates a lower bound to the condition number of a square matrix. it returns a matrix of the same size which contains the larger of the elements in each matrix. 90) Calculates an orthonormal basis for the range of a matrix.(p. 90) Calculates the norm of a vector or matrix. 90) Solve a square matrix equation where the matrix can have certain properties to increase the CPU time. 36) Sorts the elements of a vector or each column of a matrix in increasing order(p.(p.(p. 90) Calculates the reduced row echelon form of a matrix.(p. 36) The product of the elements of a vector or each column of a matrix.(p.(p. of a square matrix.(p.(p.(p. 36) The minimum element of a vector or each column of a matrix. 79) Calculates the singular value decomposition of a matrix.(p.(p.(p.(p.(p.(p.(p.(p. 90) Calculates the determinant of a square matrix.(p.(p. 57) The maximum element of a vector or each column of a matrix.(p.(p. of the elements of a vector or each column of a matrix. 36) The cumulative sum between successive elements of a vector or each column of a matrix. 36) The norm of a vector or a matrix. 90) Calculates the inverse of a square invertible matrix. 90) Calculates an orthonormal basis for the null space of a matrix. 90) Estimates the rank of a matrix. 90) Calculates some eigenvalues and eigenvectors of a square matrix.Appendix: Reference Tables Data Manipulation Commands cumprod cumsum errorbar hist max The cumulative product between successive elements of a vector or each column of a matrix.(p. 90) Calculates the condition number of a matrix.(p. Alternately. if it has two arguments.

(p. i. 92) Greater than. 93) Logical OR. 92) Not equal to.(p.(p.(p.(p.(p.(p. 93) Logical NOT.(p.(p.(p.. 94) Executes statements if certain conditions are met. 94) Logical Functions all any exist isequal find ischar isempty isfinite isinf islogical isnan logical True if all the elements of a vector are true. 93) A short-circuiting logical OR. 92) ˜ xor && || ˜ Flow Control break case continue else elseif end error for if otherwise switch while Terminates execution of a for or while loop. 93) < <= == > >= = strcmp Less than..e.Appendix: Reference Tables Logical and Relational Operators & | Logical AND. 99) False if this name is not the name of a variable or a ﬁle. 99) The indices of a vector or matrix which are nonzero. 94) Terminates the scope of the for. 99) Generates a matrix with 1 in all the elements which are ﬁnite (i. 94) Begins the next iteration of a for or while loop immediately.(p. 94) Selects certain statements based on the value of the switch expression.(p. 94. 99) True if the matrix is empty.(p.(p.(p. if.(p. 94) Repeats statements as long as an expression is true.(p.(p. 99) True for a logical variable or array.(p.(p.(p. 94) Part of the switch command.(p. 110) Repeat statements a speciﬁc number of times. 94) Used with the if statement. operates on the columns of a matrix. 92) Less than or equal to. []. 99) True if a vector or array contains character elements. 93) A short-circuiting logical AND.(p. 93) Logical EXCLUSIVE OR.(p.e. not Inf or NaN ) and 0 otherwise. 94) Used with the if statement. 110) Displays the error message and terminates all ﬂow control statements.(p.(p. 99) Generates a matrix with 1 in all the elements which are NaN and 0 otherwise.(p. 99) True if any of the elements of a vector are true. 92) Greater than or equal to.(p. (p. 92) Comparing strings. switch. and while statements.(p.(p. 92) Equal. 94) Part of the switch command.(p.(p. 99) 156 . 99) Converts a numeric variable to a logical one.(p. 99) Tests if two (or more) arrays have the same contents. 99) Generates a matrix with 1 in all the elements which are Inf and 0 otherwise.(p.(p. operates on the columns of a matrix.(p.

(p. 112) Executes a function speciﬁed by a string.(p. 110) Ends a function. it is contained here. 104) List all the breakpoints. 104) Change the workspace down to the called function. 104) Change the workspace to the calling function or the base workspace.(p.(p.(p.(p. 145) Unswitches the ﬁrst half and the second half of the elements of a vector. 110) Number of output arguments supplied by the user.(p. 145) Switches the ﬁrst half and the second half of the elements of a vector. 110) Discrete Fourier Transform fft fftshift ifft fftshift dst idst The discrete Fourier transform.(p. 110) Terminates the function immediately. 110) Executes MATLAB statements contained in a text variable. 104) Quit debugging mode and continue execution of the function. it can be shared between diﬀerent functions and/or the workspace). including the line numbers. 110) Stops execution in an m-ﬁle and returns control to the user for debugging purposes. 110) “Groups” output arguments together. 145) The discrete sine transform. 104) Number of input arguments supplied by the user. 104) List the current function. 104) Continue execution. 145) The inverse discrete sine transform. 110) Displays the error message and terminates the function.(p.(p. 104) Set a breakpoint.e.(p.(p.(p. 110) “Groups” input arguments together. 104) Display all the calling functions. 112) Begins a MATLAB function.(p.(p. 104.(p.(p. 110) Debugging Commands keyboard dbstep dbcont dbstop dbclear dbup dbdown dbstack dbstatus dbtype dbquit return Turns debugging on. 104.(p. 104) Quit debugging mode and terminate the function. 104) Remove a breakpoint.(p. 110) If eval “catches” an error.(p.(p. 110) Deﬁnes a global variable (i.(p. 145) 157 .(p.(p.(p. Only required if the function m-ﬁle contains a nested function.(p.(p.(p.(p.(p. 94. 104) Execute one or more lines.Appendix: Reference Tables 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.(p. 145) The inverse discrete Fourier transform..(p. 112) Deﬁnes a local variable whose value is to be saved between calls to the function.

(p.(p.Appendix: Reference Tables Sparse Matrix Functions speye sprand sprandn sparse spdiags full find nnz spfun spy spconvert Generates a Sparse identity matrix. 118) Generates a sparse matrix elementwise. (p. b] with given boundary conditions and an initial guess for y. 118) Sparse uniformly distributed random matrix.(p. multi-step method. 118) Applies the function to a sparse matrix.(p. multi-step method. y ) = 0. 118) Plots the locations of the nonzero elements of a sparse matrix.(p. 120) Stiﬀ ode solver. 124) Boundary-Value Solver bvp4c bvpset bvpinit deval Numerically solves y (x) = f(x. 118) Converts a sparse matrix to a full matrix. (p.(p. 120) Stiﬀ ode solver. 118) Time Evolution ODE Solvers ode45 ode23 ode113 ode15s ode23s ode23t ode23tb ode15i odeset Non-stiﬀ ode solver. variable-order. variable-order.(p. 118) Generates a sparse matrix by diagonals. 133) Assigns values to properites of bvp4c.(p. one-step method. 129) Assigns values to properties of the ode solver. y. one-step method. trapezoidal method. 120) Stiﬀ ode solver. (p. 120) Stiﬀ ode solver.(p. 120) Non-stiﬀ ode solver.(p. 133) Interpolate to determine the solution desired points. 133) 158 . fourth-order. one-step method. 133) Calculates the initial guess either by giving y directly or by using a function y = initial guess function(x). 118) Sparse normally distributed random matrix. 120) Stiﬀ ode solver.(p. y) for x ∈ [a.(p. second-order. multi-step method for the fully implicit ode f(t. second-order.(p. (p. y).(p.(p.(p. 118) Generates a sparse matrix given the nonzero elements and their indices. 118) Finds the indices of the nonzero elements of a matrix. variable-order.(p. 120) Non-stiﬀ ode solver.(p.(p. second-order. one-step method for the ode y = f(t.(p. 118) Returns the number of nonzero elements in a matrix.

(p. and fminsearch.(p. 146) Matrix logarithm. 135) Does three-dimensional interpolation.(p. 146) Matrix square root.(p.(p. (p. 138) Numerically calculates a local minimum of a one-dimensional function. 146) 159 .(p.(p. 135) Numerically calculates all the zeroes of a polynomial. 138) Numerically calculates a local minimum of a multi-dimensional function. 135) Calculates the coeﬃcients of a polynomial given its roots.(p.(p.(p.(p. 135) interpolates a piecewise polynomial calculated by pchip or spline.(p. (p. 135) Does two-dimensional interpolation. 135) Evaluates a polynomial at a point. 138) Numerically evaluates an integral using Simpson’s method. 135) Calculates the derivative of a polynomial. 138) Numerically evaluates an integral using the adaptive Gauss-Lobatto method.(p. 138) quadl Numerical Operations on Polynomials interp1 interp2 interp3 pchip poly polyder polyfit polyder polyval polyvalm ppval roots spline Does one-dimensional interpolation. 138) Numerically evaluates an integral using the adaptive Gauss-Kronrod method. 146) Evaluate general matrix function.(p.(p.(p. 135) Calculates the least-squares polynomial of a given degree which ﬁts the given data. 135) Calculates the integral of a polynomial. 138) Allows you to modify the parameters used by fzero. 135) Evaluates a polynomial with a matrix argument.(p.(p. 138) Numerically calculates a zero of a function. fminbnd. 135) Cubic Hermite interpolation.(p.(p.(p. 135) Matrix Functions expm funm logm sqrtm Matrix exponentiation.(p.(p. The interval can be inﬁnite and/or the function can have an integrable singularity.Appendix: Reference Tables Numerical Operations on Functions dblquad fminbnd fminsearch optimset fzero quad quadgk Numerically evaluates a double integral. 135) Cubic spline interpolation.

Appendix: Reference Tables 160 .

1).1751 ˆ b 2 ˆ . 2.1) ˆ 1. 3.diag( ones(n-1.5 % or C = sqrt(A) A A % or mean(R(:)) b) ˆ ˆ B 2 ˆ C.3637e+07 .diag( ones(n-1.9. 1 ) .9. 7 8 10] B = A . deg = pi/180.6a) b) c) d) e) 2.diag( exp([2:n]).9. ab = 79.ans > > (1.6. and 4.7.2e20 .10.10. 5:8.5) 2.1). c = sqrt(a 2 + b 2 .7a) ˆ A = [ ones(6.tril(A.:) A = 4*eye(n) . 1.10.10.3) 2.2*a*b*cos(ab*deg)) + ˆ c = sqrt(a 2 ˆ 6.9.1a) or > > answer: b) > > > > a = 3. A(1. b = 5.10.-1) x = [0:30] . 1 ) . 5 6 7 8.Solutions To Exercises These are the solutions to the exercises given in subsections 1.2) 1.7. 13 14 15 16] A = [1:4.:) = (-9/5)*A(2.1).7.1) = 5.4) help fix or doc fix.10. 9:12.3) > > diary triangle. cos(2*th) .10) = -5 A = A .2) 2. im] = max(R ) mean(mean(R)) S = sin(R) r = diag(R) A = [1 2 3. -1 ) A = diag([1:n].2*a*b*cosd(ab)) > > format long > > c answer: 6.6850e+06i ˆ ˆ > > th = input( th = ). 2 ˆ 161 .175085147187636 > > > > or > > asind( (b/c)*sind(ab) ) answer: 4.4a) b) 2.9. 4 5 6.9448e+01 format short e asin( (b/c)*sin(ab*deg) ) / deg c) d) 1. 2) .(2*cos(th) 2 . 9 10 11 12. 2 ˆ % or x = [0:30]. A(6.10. .10.7.1i*12 20) (1/3) answer: 1.diag( ones(n-1.4) zeros(6) ]. -1 ) b) 2. 2.1a) > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > A = [1 2 3 4. 2 ˆ R = rand(5) [m.5 % or B = sqrtm(A) C = A.:) + A(3. 13:16] A = [ [1:4:13] [2:4:14] [3:4:15] [4:4:16] ] A(2.

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

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

Solutions To Exercises 164 .

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 .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 . The octal and decimal representations of the bit patterns are shown along 165 .

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. ˆ 166 . 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.ASCII Table with a description of the character symbol. For example.

104. 58. 158 bvpinit. 157 dbstop. 26. 149 cputime. 6. 56. 84. followed by symbols. 104. 152 csc. 149 atan. 154 ceil. 13. 64. 64. 154 celldisp. 154 det. 104. 149 acscd. 43. 62. 13. 85. 155 condest. 30. 149 acos. 13. 100. 60. 150 167 . 56. 149 asin. 150. 156 asec. 64. 149 cscd. 157 dbtype. 149 acsch. 149 coth. 94. 13. 149 asech. 58. 14. 155 deval. 13.Index In this index MATLAB commands come ﬁrst. 138. 157 dbcont. 82. 13. Note: If an item is a primary topic of a section. 149 cotd. 64. this is indicated as well as the page number (in parentheses). 155 clabel. 27. 104. 36. 155 conj. 13. 154 char. 149 asinh. 99. 156 bsxfun. 16. 153 class. 133. 13. 14. 89. 64. 149 acsc. 57. 157 dbstatus. 46 chol. 155 dbclear. 46. 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. 23. 149 cosd. 94. 46. 133. 94. 82. 35. 76. 13. 154 close. 152 caxis. 33. 64. 149 cosh. 150 cumprod. 97. 149 csch. 157 dblquad. 35. 62. Note: When an item appears in a box at the end of a subsection. 152 diary. 13. 104. 149 cot. 60. 149 asecd. 7.e. 8 clf. 149 continue. 104. 60. an appendix. 152 all. or a subsection. or in the reference tables in the appendix. 13. 8. 152 danger in using. 104. 37. 54. in this document). 110. 153 cos. 94 cat. 45. 47. 153 contourf. 76. 131. MATLAB functions abs. 51. 84. 17. 153 contour3. 9. 13. 27. 131. 76. 155 cumsum. 54. 157 dbstack. 89. 149 acosd. 149 acot. 13. 156 diﬀerent than in C. 13. 131. 85. 63. 133. 149 acotd. 99. 35. 154 colorbar. 157 dbstep. 80. 149 any. 149 atanh. 157 demo. 43. 13. 60. 62. 156 angle. 63. 98. 149 addframe. 62. 153 cond. 130. 153 ballode. 104. 13. 3. 13. 13. 132 case. 58. 154 axis. 89. 13. 149 asind. Only then does the index begin with the letter “A”. 156 contour. 13. 104. 48. 154 addpath. 152 bvp4c. 13. 158 diag. 13. 63. 154 classdef. 104. 60. 157 dbup. 150 csvwrite. 47 clear. 149 cell. 13. 14. 157 dbdown. 12. 60. 148. 13. 13. 36. 149 acoth. 149 acosh. 13. 58.. 36. 35. 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. 149 atan2. 124 break. 159 dbquit. 89. 153 colormap. 45. 13. 158 bvpset. 149 atand. it is underlined. 149 avifile. 149 csvread.

64. 33. 86. 154 ginput. 150 feval. 153 load. 149 fminbnd. 154 ischar. 159 interp3. 82. 154 getfield. 32. 83. 155 eigs. 153 ezsurf. 93. 52. 2. 118. 89. 135. 31. 27. 107. 143. 56. 13. 28. 149 image. 155 else. 159 expm1. 57. 77. 27. 53. 16. 64. 156 islogical. 13. 159 logspace. 97. 101. 159 interp2. 159 fopen. 40 input. 102. 92. 155 mean. 112. 55. 141. 79. 153 ezmesh. 35. 146. 99. 16. 157 fft. 150 fscanf. 148 hilb. 14. 41. 50. 148 fplot. 12. 154 fill. 46 int16. 82. 82. 64. 156 keyboard. 54. 57. 156 exp. 17. 46 funm. 13 eye. 87. 99. 13. 13. 98. 159 fzero. 61. 155 max. 45. 158 fix. 159 interpn. 54. 99. 159 gca. 87. 157 edit. 112. 47. 153 ezplot3. 14. 9. 156 loglog. 153 meshgrid. 54. 152 isa. 59. 152 flipud. 57. 10. 36 disp. 55 log. 153. 149 false. 86. 99. 90. 153 ezpolar. 25. 94. 156 format. 46. 157 lasterr. 99. 107. 89. 4. 17. 89. 58. 154 gcf. 59. 62. 157 fieldnames. 83 doc. 63. 138. 154 isfinite. 67. 111. 65. 138. 94. 152 inline. 84. 153. 99. 110. 64. 76. 155 hold. 36. 156. 149 fliplr. 99. 65. 155 eval. 152 floor. 151 hist. 13. 25. 91. 156 isnan. 157 errorbar. 42. 110. 85. 21. 151 fclose. 13. 154 length (number of elements in). 60. 59. 97. 136. 96. 156 isfield. 136. 15. 151 ezcontour. 46. 73. 107. 94. 16. 150 int8. 56. 145. 100. 14. 99. 31. 40. 46 interp1. 143. 62. 157 if. 61. 135.6 (31). 45. 156 end. 57. 52. 97. 60. 48. 154 fprintf. 94. 110. 148 helpbrowser. 148 lu. 145. 156 isinf. 84. 157 fftshift. 84. 17. 96. 157 imag. 66. 59. 60. 153 ezplot. 94. 35. 141. 115. 20. 16. 52. 94. 20. 57. 107. 153 find. 67. 67. 65. 153 idst. 155 linspace. 138. 148. 15. 99. 12. 46 int32. 23. 110. 83. 45. 58. 135. 11. 149 log10. 156. 60. 153 fill3. 67. 99. 42. 157 legend. 157 ifftshift. 141. 57. 104. 36. 154 heaviside. 155 ipermute. 116. 112. 111. 135. 16. 60. 156 elseif. 149 log1p. 153 factorial. 89. 99. 157 gtext. 149 logical. 34. 21. 150 ind2sub. 141. 54. 37. 112. 57. 83. 15. 105. 158 function. 145. 153 logm. 62. 64. 57. 64. 57. 150 full. 157 error. 154 get. 10. 153 168 . 157 events. 53. 23. 103. 58. 154 global. 11. 157 echo. 154 getframe. 156. 60. 153 dst. 60. 47 exist. 153 lookfor. 145. 98. 153 ezcontour3. 155 mesh. 156 ifft. 159 inv. 46 drawnow. 149 expm. 23. 154 figure. 154 importdata. 59. 96. 145. 110. 150 for. 149 help. Subsect. 4. 148 double. 99. 137. 54. 145. 61. 145. 146. 13. 90. 13. 93. 104. 111.diff. 118. 157 function handle. 154 guide. 17. 156 isempty. 151 linsolve. 150 be careful. 105. 63. 100. 84. 115. 91. 8. 51. 159 fminsearch. 46 int64. 92. 152 eig. 117. 156 isequal. 146. 8.

154 sign. 53. 159 polyint. 137. 65. 83. 81. 94. 45. 133. 154 strcmp. 57. 57. 154 sec. 149 tand. 75 plot3. 153 svd. 138. 159 rot90. 55. 117. 28. 60. 16. 13. 57. 42. 155 mod. 102. 82. 149 secd. 151 ode15i. 61. 149 movie. 133. 135. 62. 55. 5 (76). 159 sprand. 154 numel. 60. 156 struct. 36. 53. 37. 30. 149 tanh. 151 sprintf. 118. 149 text. 103. 134. 27 reshape. 110. 154 nargin. 60. 118. 100. 150. 158 spfun. 159 primes. 152 subplot. 57. 76. 124. 23. 158 ode23. 135. 102. 13. 149 sqrtm. 155 save. 134. 52. 152 sscanf. 89. 49. 42. 89. 158 spdiags. 153 std. 95. 158 ode15s. 135. 101. 110. 21.methods. 112. 48. 117. 137. 135. 88. 65. 118. 153 poly. 120. 13. 149 size. 102. 133. 155 num2str. 118. 153 nnz. 37. 151. 118. 94. 57. 151 sort. 36. 89. 42. 155 profile. 148 properties. 25. 54. 128. 150 prod. 94 tan. 150. 152 persistent. 21. 152 real. 135. 159 quadl. 74. 46 sinh. 155 rats. 45. 57. 50. 76. 151 optimset. 30. 89. 13. 158 spconvert. 82. 151. 159 quadgk. 135. 13. 27. 118. 21. 151 randn. 89. 149 sech. 58. 110. 76. 158 sqrt. 13. 159 orderfields. 87. 13. 34. 159 rand. 58. 13. 153 line properties. 146. 46. 151 randperm. 115. 80. 65. 134. 155 switch. 138. 152 print. 116 speye. 133. 159 polyvalm. 66. 96. 99. 157 ndgrid. 110. 159 polyfit. 33. 44. 136. 110. 155 quad. 59. 158 sprandn. 153 polar. 115. 158 sprandsym. 149 rem. 151. 158 ode23s. 159 ppval. 41. 47 qr. 153 toc. 159 permute. 120. 158 ode23tb. 153 set. 57. 156 path. 60. 123. 152 return. 17. 35. 158 ode45. 152 pchip. 149 sin. 157 pinv. 117. 149 repmat. 51. 158 ode23t. 60. 117. 20. 53. 155 str2num. 35. 154 shg. 45. 158 ones. 36. 137. 154 orth. 56. 59. 21. 62. 155 null. 157 nargout. 20. 120. 135. 109. 118. 156 diﬀerent than in C. 153 semilogy. 158 ode113. 157 rmfield. 89. 128. 88. 116. 21. 27. 52. 152 title. 88. 20. 159 squeeze. 14. 134. 36. 43. 47 min. 149 semilogx. 154 tic. 13. 118. 67. 154 spy. 51. 13. 149 rref. 13. 148 saveas. 155 otherwise. 138. 20. 89. 138. 155 plot. 154 stairs. 151 rank. 134. 13. 158 odeset. 120. 116. 152 169 . 120. 117. 34. 135. 135. 132. 153 sum. 36. 149 sind. 129. 159 polyder. 154 movie2avi. 154 sub2ind. 158 spline. 153 pol2cart. 155 sparse. 118. 155 surf. 120. 92. 105. 53. 52. 120. 158 norm. 13. 45. See Line properties using set rather than plot. Sect. 13. 110. 135. 118. 42. 25. 21. 23. 36. 154. 60. 79. 159 polyval. 20. 154 setfield. 152 pause. 104. 153. 149 single. 152 round. 158 diﬀerences from diag. 154 roots. 57.

153 while. 156 who. 69 pause rippling2 (GUI example).*. pseudoinverse of Abort current statement. . 110. 27. 61. 150 warning about matrix division. 131 nlode all (boundary value ode). 17. 154 uiwait. 150 . 53. 114 gravity ode (force of gravity example). 149 Accuracy. 110. 27. 29. 77. 144 fibonacci (recursive code for Fibonacci series). 147 :. 115 get intervals slowly (non-vector operations example). 101 rippling (plot surface in time). 27. 102 vdp ode (van der Pol’s ode). 23. 156 !. 147. 95. 35. 103 nested ex (example of nested functions).toeplitz. 153 zeros. 130 nlode bc2 (boundary conditions for nlode). 92. 147. 2. 156 =. 132 nlode bc (boundary conditions for nlode). 46 uint32. 113 myheaviside (the Heaviside function). 28. 65. 73. 143 fft ex2 (Fourier transform example). 40 view. 13. 82. 150 . 147 <. 93. . 21. 154 vander. 71 prealloc (example of preallocating arrays). 151 . 7. 74 spruce (example using optional arguments). 110 fzero example (Calling fzero using a nested function). 68 running gaussians (plot Gaussians in time). 148 uicontrol. 92. 19. 78. 58. 93./.. 156 >=. 81. 46 uipanel. 28 . 108 nlode (boundary value ode).. Subsect. 15. 2. 24. 147. 147 . 18. 156 ˜ ˜ 170 . 13. 7. 92. 156 >. Subsect. See Conjugate transpose AT . 19. 69. 7. 16. 149 addframe. 154 uiresume. 61. 30. 57. 16. 19. 27. 149 acosd. 27. 130 nlode y ic (initial conditions for nlode). 149 acsch. 51 sample movie (example making movie). 76. 13. 73. 27. 99. 92. 156 &&. 29. 21. 147.3 (22). See Transpose A+ . 92. 150 *. 157 varargout. 152 triplequad. 24. 6. 11 acos. 73. 151 varargin. 136 get intervals fast (vector operations example). 30.2 (22). 147. 13. 7. 60. 27. 20.. See Matrix. 151 type. 107. 128 hilb local (calculating Hilbert matrix). 93. 28. 93. 151 . 93. 93. 30. 157 vectorize. 10 principle. 65. 156 |. 60. 154 addpath.. 156 &. 13. 126 Symbols +. 92. 130 nlode1 (boundary value ode). 9. 95. 134. 149 acoth. 25. 150 \. 93. 30. 100. 122 fft ex1 (Fourier transform example). 135. 13. 16. 147 %. 150 . 131 nlode2 (boundary value ode). 53. 149 acotd. 15. 29. 30. 150 exception to. 17. 33. 98. 154 uint8. 6. 153 []. 15 abs. 7. 151 zlabel. 30. 94. 147. 110. 101 hilb2 (calculating Hilbert matrix). 13. 92. 30. 7. 156 ylabel. 152 true. 149 acot. 14. 150 . 150 /. 138 triu. 92. 147 Local m-ﬁles in companion zip ﬁle colormap example (modifying the colormap). 69. 30. 100. 95. 13. 147.. 93. 92. 22. 58. 73. 17. 121 duffing p2 (Duﬃng’s ode). 149 acsc. 29 -. 7. 39 ↑ up-arrow key. 63 duffing closure (Duﬃng’s ode). 152 @. 94. 24. 149 acscd. 144 fft ex3 (Fourier transform example). 30. 57. 28. 107. 21. 65. 156 <=. See factorial ˆ ˆ A AH . 7. 9. 147. 27. 152 all. 46 uint16. 156 ||. 148 whos. 15. 28. 27. 149 acosh. 122 duffing ode (Duﬃng’s ode). 18. 153 xor. 107. 147 . 13.\. 150 . 92. 46 uint64. 13. 151 tril. 95. 27. 131 pause rippling (GUI example). 7. 7. 148 xlabel. 156 . 156 ==. 30.

36. 22. 2. 158 bvpset. 105. 147 +. 22. 30. 41 comparing strings. 150 *. 13. Subsect. 26. 28. 150. 47 clear. 76–79 See also Matrix Average value. 154 char.4 (42). 7. 3. 43. 133. 154 Cell array. 27. 154 Closure. 153 colormap.AND (logical operator). 41.1 (6) case. 47. 147. 30. 46 handle. 39. 149 Anonymous functions. 60. Sect. 132. 7. 29. 13. 51. 19. 7. 47 subclass. 16. 64 Colon operator. 156 bsxfun. 43. 133. 156 angle. Subsect. 1. 27. 83. 147. 42. 94. 64. 13. 54. 2. 98 ASCII character representation. 149 asech. 62. 154 C++ (programming language). 47 event. 154 Class. 150 . 99. 61. 1. 14. 46 Character string. 95. See Initial-value ordinary diﬀerential equations Binary format. 2 (17) See also Matrix and Multidimensional arrays and Vector and Cell array equal (are two arrays). 149 atan2. 64. 30. 28 . 126–128 ballode. 3 ˆ ˆ B Ball. 89. Subsect.2 (22). 147. 9. 62 See also clf and close clf./. 82. 30. 148 ˆC. 152 Catching errors. 66 tick marks outside plot. 60. 111 Calculator. 28. 148 any. 153 class. 62. 158 bvpinit. 156 Arithmetic progression. 150 . 47 listener. 149 asind. 30. 41 converting to. 150 /. 30. 76. 62. 82. 42 putting a number of strings in lexicographical ordering. 33.3 (41). 13. 81.3 (22). 150 . 84. 147. 77. See RGB components Command. 155 Cholesky decomposition. 7. 28. 130. 57. 22 Arithmetical operations. 43 TEX commands in. 152 danger in using. 28. 150 . 45. 93. 94. Subsect. 131. 43. 61. 58. 3. 94. 29 Array. 111 caxis. 149 asin. Subsect. 37. 154 ceil. C 7. 147. 92. 30. 84 clabel. 46 value. 42 executing. 66 chol. 3. 63. 62. 66 C 15. 65. 62. 147. 153 Colors. 93. 98 celldisp. 45. 63 colorbar. 165 asec.5 (45) callback. 132 break. Subsect. 154 close. 47 classdef. Sect. 131. 149 asecd. 149 atanh. . 29 -. 150 elementwise. 150 \. 13. 8 Clear (a ﬁgure). 30. 2. 47 user-deﬁned. See Function ans. 11 (129). 7. 48 See also linspace Color map. 111 multiline. 158 171 . 7. 55 Boundary-value ordinary diﬀerential equations. 8. 64. 133. 30.*. 29. 13. 154 axis. 35. 106. 12. 53 equal (are two cell arrays). 29. 41. 8. 84. 45. 63. 97. 149 Augmented matrix form. 150 warning about matrix division. 39. 27. 9 cat.1 (6). 149 atan. 17. 8. 46. 34 avifile. 9. 7. Subsect. 147. Subsect. 91 concatenating. 147 possible ﬂoating-point errors in. 47 fundamental. 152 bvp4c.4 (27). 156 diﬀerent than in C. 13. 64. 27. 136 Clown. 13. 153 Axis changing numbers on. 122. 124 Bessel’s equation. 149 asinh. 94 Case sensitive.(programming language). 76. 46. 45 fundamental (table). 27. 28. 147. 64. 150 exception to. 78. 133. 154 appending to. 30. 149 atand. 158 continuation method. 43. 149 cell.\.

117. 158 diag. 112. 155 opening ﬁles. 30. 82. 152 Diagonals. 80. 58 contour3. 149 csch. 54. 35. 133. 23. 102 deﬁnition of. See Interpolation cumprod. 148. 3. Subsect. 155 Eigenvalues. 89. 13. Subsect. 146. 9. 157 Duﬃng’s equation.4 (10) misinterpreting. 86. 157 dbstatus. 149 cosh. 110. 14 Complex numbers. 13. 13 Exponentiation. 152 eig. See Length of a vector eval. 17. 102. 104. 84. 153. 54 errorbar.8 (33). 35. 157 Debugging m-ﬁles. 110. 157 dbstep. 86. 17. 13. 149 coth. See Fourier transform Discrete sine transform. 147 Complex conjugate. 153 Control ﬂow. 56. 15. 156 exp. 92. 82. 51.5 (45) fundamental fundamental (table). 39. 53. 54. 54. 54. 60. See Matrix diary. 157 dbup. 149 cos z. 29 double. 1. 104. 15. 90. 63. 111. 156 elseif. 157 eps. 138. 149 expm. 157 edit. 16. 132 continue. 60. 148 See also Machine epsilon Erase (a ﬁgure). 83 reading into MATLAB. 31. 94. 150. 47 EXCLUSIVE OR (logical operator). 101.Command (cont. 36 Digits of accuracy. 157 dblquad. 36. 13. 156 exist. 15.) See also Function Comment character. 149 cotd. 156. 89. 56. 62 See also clf error. 64 echo. 4. 145. 157 dbstack. 157 172 . 36. 107. 13. 110. 85. 155 Euclidean length. 147 variable. 82. 89. 82. Subsect. 157 dbstop. 155 Condition number. 85. 133 closing ﬁles. 92. 54. 91. 149 cot. 8. 31. 13. 13. 14. 155 Determinant. 159 expm1.6 (13) Conchoid of Nicodemes cond. 85 deval. 155 cumsum. 7. 13. 104. 9. 27. See Initial-value ordinary diﬀerential equations E ez . 147 Continuation method. 58. 23. Subsect. 3. 157 dbdown. 60. 155 condest. 13. 150 diff. 58. 15. 95. 104. 84. 157 dbcont. 46 dbclear. 149 cscd. 35. 156 end. 57. 104. 64 det. 89. 150 Cubic splines. See Function m-ﬁle and Script m-ﬁle demo. 9. 57. 83 Discrete Fourier transform. 148 Documentation (MATLAB). 12. 86. See Matrix conj. 83 See also disp and fprintf doc. 2. 94. 14 Earth. 104. 64. 2. 145. 42. 3. 16 Dot product. 89. 104. 104. 46 drawnow. 131. 14. 7. 86 Eigenvectors. Subsect. 56. 154 Demonstration program. 152 csc. 9. 10. 13. 150 csvwrite. 104. 61 dbtype. 94. 159 dbquit.6 (31) suppressing. 93. 89. 6. 8. 149 Conjugate transpose. 150 Data types. 58. 7. 6. 60. 156. 94. 86. 157 events. 93. 27. 16. 155 else. 18. 99. 6. 10 disp. 83 manipulation. 14. See Fourier transform Display formatting the. 150 writing from MATLAB. 16. 1. 30 cputime. 16. 82. 60. 153 contourf. 157 Error bars. 102 eigs. 156 contour. 155 Cursor entering current position. 104. 149 CPU. 56. 104. 28 D Data best polynomial ﬁt to. 149 csvread. See Programming language cos. 89. 48. 93. 14 cosd. 153 dst. 153 Contour plot. 19 See also Transpose Continuation (of a line).

11. 110. Subsect. sprintf.6 (31). 40 built-in. 99. 101. 138 Fourier transform. 53. 141. 13. 152 flipud. 110. 109 local minimum of. 3. 21. 82. 83 Fourier series. 59. 14 (138) discrete. 102 function (required word). See Programming language fminbnd. 90. 83. 149 Flops (ﬂ oating-point operations). 25. 156. 118. and sscanf). 158 function. 1. 109 Functions (mathematical) See also Polynomials common mathematical. 14 (138) complex. Subsect. 156 format. 42. 159 G Gauss-Kronrod quadrature (for numerical integration). 12 debugging. 60. 153 ezplot. 150 speciﬁcations (format). 40 primary. 158 Finite diﬀerences. 136. 60. 136 numerical operations on. 100. See Closure passing function name in argument list. 84. 41. 150 feval. Subsect. 153 fill3. 63. 84. 46 Function m-ﬁle. 103. 10. 153 ezpolar. 82. 118.3 (99) debugging. 138. 144 fast (FFT). 63. 84. 106 pass by reference. 100 pass by value. 100 variable number of. 82. Sect. 149 fliplr. 148 Format speciﬁcations (in fprintf. 44 warning. 157 comments in. 111. 57. 52. 103. 60. 25. 8. 173 . 83. 100.1 (39). 137. 157 saving parameters in. 54. 112. Subsect. 101 name of. 157 Fibonacci sequence. 153 ezplot3. 83. 8. 137 Gauss-Lobatto quadrature (for numerical integration). 84. 115. 117. 94. 64.2 (40). 109 return. 151 FALSE (result of logical expression).3 (99) anonymous. 14 warning about user-deﬁned m-ﬁles. 23. 9. 57. 104. 150 for. 64. 40 warning.5 (11) deﬁnite integrals of. 107.Extrapolation. 54. 10. 99 passing name into. 16 commands in. 109 passing arguments indirectly. 157 Function. 29 Flow control. 100 conﬂict between function and variable name. 145. 152 Floating-point numbers. 143. 107 ending. 153 ezcontour3. 136. 142 fplot. 96. 157 fftshift. 100. 105–106 subfunctions in. 157 fft. 97. fscanf. 14 (138). 23. 99 diﬀerences from command. 104 deﬁnition line. 58. Sect. See Structure fieldnames. 135. 139 real. 22 Floating-point operations. 136. 138. 107 error. 153 find. 151 ezcontour. 11 false. 148 Format options (in format command). 145. 145. 159 fzero. 35 fix. 149 Factorial function. 107. 111. 138. 99. 154 figure. 116. 92 Fast Fourier transform. 153 ezmesh. 99. Subsect. 39. 83 speciﬁcations (format). 27. 62. 104 names of. 8. 138. 146. 110. 13. 64. 153 ezsurf. 11. See Power fscanf. 59. 45. 15 nested. 15. 93. 60. 134 See also Interpolation eye. 156. 60. 154 fill. 59. 157 example using multiple input and output arguments. 138 “hijacked”. 112 piecewise. 27. 11. 101. 107 order in which MATLAB searches for functions. 2. 110. See Fourier transform fclose. 157 discrete sine. 3. 40 input and output arguments. 83 full. 110 Field. 104–105 “grouping” together. 107 Function handle. 159 zeroes of. 150 printing a matrix. 99. 110. 154 fprintf. 13. 107 private. 64. 3 end statement. 44 function handle. 137 funm. Subsect. 83 Frequency. 15. 159 fminsearch. 141. 11. See Flops floor. 159 fopen. 59. 157 inline. 52. 41 recursive. 104. 153 F factorial. 20. 137. Sect. 94.

120. 9. 6. 134 inv. 87. 137 interp1. 128. 158 absolute error. 67. 56. 150 int8. 149 Helix. 100. 159 Interpolation. 51 multiple windows. 48 Gravity. 47. 99. 112 hist. 4. 4. 65 printing.Gauss-Lobatto quadrature (cont. 62. 157 imag. 91. 154 global. 120. 118–125 ﬁrst-order system. 20 See also eye idst. 49 demonstration. 4 (48) advanced techniques. 55. 158 ode15s. 61. Sect. 135 cubic. 56. 158 ode23s. 40 Inline functions. 65.8 (15) getting help. 66. 99. 56. 157 Gram-Schmidt algorithm. 57. 120. 126 gtext. 99. 103. 94. 89 Graphics. Subsect. 85. 134. 155 ipermute. 148 Hermite polynomials. 65. 153 I I. 156 Sect. 150 ind2sub. 148 Help facility. 96. 4. 46 int64. 16. 141. 135. 53. 76. 46 int16. 98. 135 how to do extrapolation. 86 get. 148 Initial-value ordinary diﬀerential equations. 120. 61–65 text properties. 126 Van der Pol’s equation. 159 interp3. 32. 145. 157 ifftshift. 158 passing parameters to. See Function. 46 int32. 154 ischar.4 (65) holding the current plot. 124 stiﬀ. 67.1 (48). 134 function ﬁle for. 149 image. 128 Duﬃng’s equation. 81. 154 Imaginary numbers. 158 ode23t. 135. 6. See Graphics heaviside. 120. Subsect. 67. 159 interpn. 156 isequal. 77. 156 ifft. 135 cubic splines. 119 statistics for. 31. 112. 17. 28. Subsect. 125–126 inline. 66 using TEX commands. 120. 101.2 (57) two-dimensional. See Interpolation hilb. Subsect. 64. 154 Generalized eigenvalue problem. 157 if. 14. 48 handle. 135 Hermite cubic interpolation. (118) Bessel’s equation. 13. 29 input. 50. 135. 120. 120. 1. 105. 73.3 (60). 154 getfield. 4. 152 Inf. 32. 122 properties of. 135 linear splines.) 137 Gaussian elimination. 159 interp2. 153 window. 154 getframe. 154 ginput. 119. 153. Subsect. 57. 158 ode23tb. 141. 134. 31. 105. 10 174 . 9. 148 searching for string. 154 changing endpoints. 9. 124 relative error. 23.5 (67) guide. 61. inline Inner product. 99. 85. 17. 89. 65 handle for an. See Function handle Handle graphics. 155 Histogram. Subsect. 154 H H . 4. 49 labelling. numerical. 120. 66 multiple plots. 61. 45. 119 adaptive step size. 119 events. 135. 4. 4. See Identity matrix i. 110. 51 customizing lines and markers. 150 three-dimensional. 46. 62 object. 16 helpbrowser. 158 ode113. 148 importdata. 145. 67. 51. 55. 158 ode45. 40. 143. 107. 81 gca. 58 help. 37. See Conjugate transpose Handle. 125 ode15i. 55. 129. 156 isempty. 152 isa. 151 Hilbert matrix. 80. 145. 101. 154 GUI (Graphical User Interface). 148 Identity matrix. 15. 118 with constant coeﬃcients. 150 properties. Subsect. 145 solvers.4 (65) saving to a ﬁle. 10. 158 ode23. 46 Integration. 154 gcf. 89. 53 hold.

25 singular.9 (36) null. 28. 25 reshaping. 79. 107. 64. 5. 20.2 (95) result of. 14. 33. 5. 77 Cholesky decomposition. 95. 156 Logical (data type). 86 deleting rows or columns. 153 load. 149 log1p. 95 LOGICAL AND (short circuiting logical operator). 8.7 (33).3 (81) linsolve.1 (18). 48. 93 Mathematical functions. 2. 77. 99. 2. 84 approximation to. 2.e. 158 K keyboard. 81 solving by linsolve. 153 lookfor. 17. 85 warning of. 93. Subsect. 15 L lasterr. 156 isnan. 25. 156 LOGICAL OR (short circuiting logical operator). 87 Jacobian.isfield. 20. 149 log10. 159 logspace. 151 elementary operations. 99. 95. 77 solving by rref. 93. 97. 92 Logical functions. 56. 156 NOT ( ). Euclidean length).3 (81). Sect. 60 Linear splines. 151 Length of a vector (i. 25 determinant of. 134 overdetermined. 148 lu. Subsect. 156 ˜ 175 . 156 Logical operators (cont. 35. 34 multidimensional. 112. 92. 22 full. 65. 77. 57. 99. 154 Lemniscate of Bernoulli. 151 empty. 16. 157 Keywords. 85 defective. 93. 73 Line properties. 146. 23. 148 Java (programming language). 95. Sect. 93. 92. 150 be careful. 148. 93. 21. 149 logical. See Determinant diagonals of. 101 pseudoinverse of. Subsect. Subsect. 153 logm. 157 Left division. 115 generating. 95. 43. 156 AND (&). 99. 115. 61. 134 solving by \. 20. 24. 84 condition number. 89 QR decomposition.. 88 positive deﬁnite. 54. 95 EXCLUSIVE OR (xor). 152 orthogonal. See null (below) extracting submatrices. 126 lower triangular part of. 91 result of. 81. 87 singular value decomposition. 92.3 (81) least-squares solution. 99. 12. 93.) J j. 17. 93. 13. 87 unit.3 (22) by submatrices. 2. 8 Kill current statement. 55 log. Subsect. 20 Hermitian. 23. Subsect. 116. 99. 35 See also norm Life (Conway’s game of). 156 Logical expression. 156 isinf. 93. 79. 81. 95. 100. 2. 88 replicating. 96. 46. 97 maximum value. 16. 117 elementary. See Interpolation Linear system of equations. 97. 78. 13. 154 isfinite. 19 Hilbert. 6. 20 inverse of. 156 Logical operators. 156 applied to matrices. Subsect. 156 loglog. 99 See also Function m-ﬁle and Script m-ﬁle Machine epsilon (eps). 104. 9 (115). 80. 98. 121. 1. 52 length (number of elements in). 27. 156 AND (short-circuit) (&&).5 (11). 13. 45. 57. See \ legend. 111. 9. 5 (76).3 (22). 54. 76–79 is not a matrix. 5 (76) underdetermined. 87. 57. 149 Matrix as column vector. 34 minimum value. 152 “masking” elements of. 89. 155 LU decomposition. 87 LU decomposition. 117 preallocation of. 87 manipulation. 111 OR (short-circuit) (||). 156 OR (|). 89 sparse. 21 individual elements. 87 M M-ﬁles. 21. 156 islogical. Subsect. 96 augmented. 148 calculation of. 155 linspace. Sect. 5. 93. 52. 92. 84. 9. Subsect. See Hilbert matrix identity. Subsect. 23.

134. 135. 110. 59. generating a. 158 norm. 153 line properties. 120. 156 Outer product. 33 mesh. 149 Monotonicity. 87. 135. 87 Frobenius. 92. 29 Overdetermined system. 135. 102. 58. 94. 120. 33. 88 upper triangular part of. 62. 88 otherwise. 154 Ordinary diﬀerential equations. 152 pchip. 41 Moore-Penrose conditions. 59 permute order. 60. 120. See Search path pause. 134. 8. 76. See Graphics plot3. 95. 120. 36. 110. 110. 52 in polar coordinates. See Vandermonde matrix max. 148 Piecewise polynomials. Subsect. 134. 34. 75 Plot. 133 roots of. 93. 138. 123. 20. 2. 92. 57. 151 O Ode. 129. 89. 159 OR (logical operator). 36. 152 Null space. See Matrix. 88 p -norm. 135. 53. 59. 19. 34 SVD. pseudoinverse of Mouse location. 95. 151 sum of elements. 35. 81 Moore-Penrose pseudoinverse. 34 mod. 60. 157 ndgrid. 152 persistent. 128. 110. 159 N NaN. 158 ode45. 148 nargin. 156 orderfields. 89. 9 path.Matrix (cont. 103. 37 ode23s. 24 tridiagonal. 156 Notation (for vectors and matrices). 34 Memory (of variables). 153 polar. 134. 88. 60. 13. 88. 53 phase plane. 124. 133 polyval. 52 a parametric function. 120. 82. 157 nargout. 126 nnz. 35 Monty Python. 42. 58.) specialized. 76. 34. See Plotting pi. See Initial-value ordinary diﬀerential equations and Boundary-value ordinary diﬀerential equations orth. 154 Multidimensional arrays. 12 (133). 134 order of. 88 num2str. See Line properties using set rather than plot. 158 ode23t. 118. 120. 135. 153 Polar coordinates. Subsect. 159 polyfit. 102. 48. 115 unitary. 60. 153 Plotting a curve. 159 diﬀerentiating. 57. 159 Polynomials. 100. 52. 135. 158 176 . test for. 36. 136. 134 evaluating.9 (36) generate grid. 151 Operator precedence. 85. 9. 89. 154 numel. 155 Orthonormal basis. 47 min. 5 null. 93. 45. 158 ode23tb. 51. 155 Norm matrix. 102. 153 methods. 55. 52 an implicit function. 155 Mean value. 49. See ginput movie. See singular value decomposition (above) symmetric. 25. 74. 27. 9. 120. 58. 133 ﬁnding minimum and maximum of. 133. 105. 24 Vandermonde.5 (30) optimset. 159 permute. 154 movie2avi. 159 polyint. 83. 117 Toeplitz. 158 ode23. 89. 57 a function. 48. 158 odeset. See Initial-value ordinary diﬀerential equations ode15i. 158 ode15s. 134 representing by vector. 134. 117. 128. 132. 159 polyder. 41. 133. 60. 121 pol2cart. 21. 87 NOT (logical operator). 53 poly. 110. 37. 153 Newton’s laws. 21. 158 ones. 152 Path. 33 mean. 105 Phase plane. 155 Minimum value. 59. 2. See Interpolation pinv. 153 meshgrid. 155 Maximum value. Sect. 158 ode113. 36. 157 uses of. 155 Null matrix. 155 plot. 60. See Linear system of equations P Parentheses. 88 vector.

2 (80). 88. 14. Subsect. 152 Principles about computer arithmetic. 50. See Inner product outer. 139. See LOGICAL AND and LOGICAL OR sign. 53 177 . 25. 100. 88 quad. 156 >. 62 rmfield. 8 (90) ﬂow control. 148 Recursion. 149 Round-oﬀ errors. 154 shg. 154 Short circuiting (logical operators). 80. 156 break out of. 23. 20 pseudorandom numbers. 20 state. 137 13 R rand. 89 Rational approximation to ﬂoating-point number. generating. 148 Save terminal commands. 92. See Random numbers Pythagorean theorem. 95 properties. 82. 139 spectrum. 20. 13. 81. 150 Printing. 149 Simpson’s method (of numerical integration). 13. 33. 139 ppval. 21. 20 recommended procedure. 55. 100. 9. 13. 87 rref. 20. 6 saveas. 21. 156 <. 156 diﬀerent than in C. 155 ˜ S Q qr. 91 switch statement. 139 frequency of. 17. 151 randn. 92. 13. 151 Random matrix.1 (90). 79. 92. 53 normal distribution. 159 Quadratic polynomial. 57. 103. 21. 137. 10. 93 continue loop. 89. 45. 20. 5 (76). 48. 9. 153 semilogy. 27.2 (95) result of. 152 return. 65. 104. 95 rem. 149 Remainder. 13. 149 sech. 79 Relational operators. 25. 10 reshape. 149 repmat. 47 Pseudoinverse. 118. 156 matrix. 52. 57. 140 average. 80. 93 needed less frequently. Sect. 76. 92. 16. See Variables Script m-ﬁle. Subsect. 154 roots. 151 rank. 138. 110. 32. 155 Product dot. 92. 20 uniform distribution. 25. 133. 153. roots of. 154 setfield. 14. 135. 11. 148 Programming language (MATLAB). 140 instantaneous. 155 QR decomposition. 135. 87 real. 22. 159 Positive deﬁnite matrix. 23. 94 while loops. 139. See Matrix Power. 81. 109 sec. 159 rot90. 7 save. 94 for loops. 149 secd. See Outer product profile. 159 quadgk. 152 round. 101. 11 print. See Matrix Pseudorandom numbers. 152 rats. 45. 104 names of. 156 ==. See Operator precedence Predeﬁned variables. 152 RCOND. 90 if statement. 80. 77 round-oﬀ errors in. 158 Random numbers. 53. 92. 53. 20. 81. 156 =. 56. 20. 9. 57. 27. 109 Reduced row echelon form. 92. 66. 85. 67. See Variables Prime numbers. See Display prod. Quote mark. 20 initial seed. 1. 94. 8. 153 set. 6 Scope. Subsect. 149 realmax.polyvalm. 149 semilogx. 133. 138. 11 randperm. 8. 89. 28. 157 RGB components (of a color). 15 Search path. 27 Request input. 109. 104 debugging. 138. 156 >=. 148 realmin. 24. 154 Scientiﬁc notation. 94. 20. 112. 139 in each mode. 5. 79. 52. 6 Save work. See Dot product inner. 82. 20 Gaussian distribution. 137. Subsect. 135. 137. 155 Rank of matrix. 152 primes. 14.3 (9). 13. 159 Precedence. 139 deﬁnition of. 156 <=. 13. 115. Sect. 36. 159 quadl.

117. 46 uint64. 105 inputting. 107. 62. 62. 36. See Initial-value ordinary diﬀerential equations vander. See Singular value decomposition switch. 94. 24. 118. See Character string text. 152 true. 146. 152 Time. 152 sscanf. 60. 118. 151 sort. 111 rerunning previous. 20. 118. 153 warning. 36. 9 conﬂict between variable and function name. 9 global. 28. 93. 149 single.2 (7) about. 134 varargin. 152 Subfunctions. 14 sind. 46 uint16. 158 spfun. 157 varargout. 23. 66 Text window. 153 multiline. 24. 69. 46 uipanel. 57. 54 Standard deviation. 13. 46 uint32. 54. 30. 89. plotting a. 149 sqrtm. 83 stairs. 92. 16 178 . 44. 33. 115. See Character string struct. 21. 12 deﬁned. 58 svd. 21. 7. 154 uiwait. Subsect. 155 SVD. 58. Subsect. 69. 1. 83 spy. 18. 149 sin z. 154. 17. 152 Transpose. 158 diﬀerences from diag. 158 sprandn. Subsect. 158 sprandsym. 15. 46 Singular value decomposition. 37. 16. 150. 27. 58 wire-frame. 154 Text properties. 120. 13. 65. 51. 34 Statements executing in text variables. 110.sin. 57. 149 Taylor series expansion. 43. 1. 151 Vandermonde matrix. 58 ﬁlled-in. 107. 154 speciﬁcations (format). 154 uint8. 48 tic. 135. 39. 51 sum. 158 spdiags. 24. 46. 118. 149 tand. 154 Structure. 34 sparse. 155 Sort numbers. 92 type. 13. See Function m-ﬁle subplot. 157 Variables. 13. 118. 154 speciﬁcations (format). 96. 42. 54 Stiﬀ ode. 95. 13. 151. 27. 149 size. 134. 151. 107.5 (11). 126 str2num. 156 String. 100. 151. 58 changing view. 94. 57. 151 TRUE (result of logical expression). 154 uiresume. 156 T T . 10 list of. 35. 149 tanh. 116 speye. 116. 155 surf. 2. 21. 154 strcmp. See Matrix toeplitz. 117. 118. 73. 98 ﬁeld. 110. 60. 30. 154 Underdetermined system. 116. 89 sinh. See cputime and tic and toc title. 9 case sensitive. 27. 153 Surface plot. 117. 34. 43. 148 U uicontrol. 53. 118. 147 std. 99. See Character string. 117. 138 triu. 98 deleting. 151 toc. equations See Linear system of V Van der Pol’s equation. 10 separating on a line. 118. 159 squeeze. 152 triplequad.7 (33) tril. 19. 9. 66 Toeplitz matrix. multiline Title for entire ﬁgure. 61. 155 Step function. 153 Stairstep graph. 151 conjugate. 118. 73. 65. 159 Splines. 151 Trigonometric functions. See Transpose tan. 36. 73. 19. See Interpolation sprand. 158 sqrt. 42. 43 sub2ind. 150. 13. 27. 145 TEX. 135. 136 equal (are two structures). 73. 158 spconvert. 151 sprintf. 158 spline. 45. 13. 42.

33 mean value of elements. 7. 8. 7. 53. 7. 34 standard deviation of elements. 105 overwriting. 148 j. 16. 3. 8 Vector average value of elements. 9. 10. 153 W while. 60. 34 sum of elements. 148 realmax. 9. 20. 148 saving.5 (112) proﬁle execution time. Subsect. 108 special cases of vectors or matrices. 61. Subsect. 153 Z zeros. 34 minimum value. 16 local. 57. 16. 25 equal (are two vectors). 17. 94. 65. 8. 9. 6. 10. 101 repeated elements. 148 whos. 148 NaN. 40 Vectorizing code.Variables (cont.3 (41) See also Character string typeless. 8. 105 string. 93. 60. 153 loading. Subsect. 92. 112 view. 7 persistent. 93. 9. 35 sort elements. row. 105 valid names. 6. 16 saving local variables in functions. 148 Inf. 34 column vs. 97 modifying. 97 maximum value. 57. 148 overwriting. 51. 9. 104 X xlabel. 91 pi. 9. 61. testing for. 9. 148 ans. 148 Workspace. 18 deleting elements. 9. 105 logical. 53. 98 generating. 95. 58. 153 xor. 8. 21. 148 realmin. 7 static. 43.) Y ylabel. 93. 65. 156 who. 34 preallocation of.1 (18) individual elements. 156 179 . 34 vectorize. 9. 2. 65. 17. 23. 148 eps. 20. 151 zlabel. 99. 6. 20 “masking” elements of. 105 predeﬁned. 148 i. 105 scope of. 58. 9.

Index 180 .

- Guang Xiao Thesis
- Probability
- FUZZ Luanan
- Quantization and Discretization at Large Scales, edited by Florentin Smarandache, V. Christianto, Pavel Pintr
- MacColl - Symbolic Logic and Its Applications (Versone 2)
- Calculus 1
- Flashcards - Quantitative Review
- Algebra a Geometria
- Natural Product Xn on Matrices, by W. B. Vasantha Kandasamy, Florentin Smarandache
- Supp Notes Calculus
- Solving Polynomial Systems
- Lecture on Algebra
- Me690 Lctr Nts
- Probability Text
- Kluwer Academic_Mathematical Problems and Proofs Combinatorics Number Theory, And Geometry - 2002
- Lecture on Differential Equations
- 160845181X
- Applied Inter Temporal Optimization
- Modern Cryptography Theory and Practice
- Finite Markov Chains and Algorithmic Applications
- 0521599938_Combinatorics
- Sergiy Koshkin- Homogeneous Spaces and Faddeev-Skyrme Models
- Primer of Bio Statistics 5Ed
- Quaternion Algebraic Geometry_Dominic Widdows
- Example Geometry Expression
- Laplace- The System of the World Vol i (534p)
- One Hundred Years of Russel
- A Compilation of the Mathematics. Leading to the Doublet-Lattice Method
- a to z sudoku
- Calculus for the Life Sciences_A Modeling Approach-Libro2011

- 08 - Capítulo Iii_final
- tracinhos_mozão
- EDITAL DE ABERTURA Nº 06-2017 EM 20_01_2017 (1)
- Código de Cores Mapa Geológico BP 01ago17
- 06 - Capítulo Ii_final
- Metodologia de Interpretação de Dados de Sensoriamento Remoto e Aplicações Em Geologia
- Introducao a interpretacao radargeologica.pdf
- Introducao a interpretacao radargeologica.pdf
- Mapa Natal
- pioix
- Cur So Matlab by Carlos Teixeira
- Coordenadas Afloramentos - Sistemas Deposicionais
- 2008 MDT GPS RTK EstudosGeologicos Vol181 Trab8
- 04 - Capítulo I_final
- Petrobras0111 Gabarito Superior 2011 1
- Petrobras0110 Gab 1605

Sign up to vote on this title

UsefulNot usefulClose Dialog## Are you sure?

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

Loading