## Are you sure?

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

1:17 p.m.)

A MATLAB Tutorial

Ed Overman Department of Mathematics The Ohio State University

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

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

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

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

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

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

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

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

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

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

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

3 6 6 7 9 10 11 13 14 15 17 17 18 22 23 28 31 32 34 34 37 38 39 40 41 42 43 46 49 50 50 59 62 67 69 75 78 78 79 82 83 84 86

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

8

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

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

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

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

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

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

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

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

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

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

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

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

2

Introduction

MATLAB is an interactive software package which was developed to perform numerical calculations on vectors and matrices. Initially, it was simply a MATrix LABoratory. However, today it is much more powerful: • It can do quite sophisticated graphics in two and three dimensions. • It contains a high-level programming language (a “baby C”) which makes it quite easy to code complicated algorithms involving vectors and matrices. • It can numerically solve nonlinear initial-value ordinary diﬀerential equations. • It can numerically solve nonlinear boundary-value ordinary diﬀerential equations. • It contains a wide variety of toolboxes which allow it to perform a wide range of applications from science and engineering. Since users can write their own toolboxes, the breadth of applications is quite amazing. Mathematics is the basic building block of science and engineering, and MATLAB makes it easy to handle many of the computations involved. You should not think of MATLAB as another complication programming language, but as a powerful calculator that gives you ﬁngertip access to exploring interesting problems in science, engineering, and mathematics. And this access is available by using only a small number of commands and function† because MATLAB’s basic data element is a matrix (or an array). This is a crucial feature of MATLAB — it was designed to group large amounts of data in arrays and to perform mathematical operations on this data as individual arrays rather than as groups of data. This makes it very easy to apply complicated operations to the data, and it make it very diﬃcult to do it wrong. In high-level computer languages you would usually have to work on each piece of data separately and use loops to cycle over all the pieces. In MATLAB this can frequently do complicated “things” in one, or a few, statements (and no loops). In addition, in a high-level language many mathematical operations require the use of sophisticated software packages, which you have to ﬁnd and, much worse, to understand since the interfaces to these packages are frequently quite complicated and the documentation must be read and mastered. In MATLAB, on the other hand, these operations have simple and consistent interfaces which are quite easy to master. For an overview of the capabilities of MATLAB, type >> demo in the Help Navigator and click on MATLAB. This tutorial is designed to be a concise introduction to many of the capabilities of MATLAB. It makes no attempt to cover either the range of topics or the depth of detail that you can ﬁnd in a reference manual, such as Mastering MATLAB 7 by Duane Hanselman and Bruce Littleﬁeld (which is over 850 pages long) or MATLAB Guide, 2nd edition by Desmond and Nicholas Higham (which is almost 400 pages long). This tutorial was initially written to provide students with a free “basic” overview of commands which are useful in an undergraduate course on linear algebra. Over the years it has grown to include courses in ordinary diﬀerential equations, mathematical modelling, and numerical analysis. It also includes an introduction to two- and three-dimensional graphics because graphics is often the preferred way to present the results of calculations. In this tutorial MATLAB is ﬁrst introduced as a calculator and then as a plotting package. Only afterwards are more technical topics discussed. We take this approach because most people are quite familiar with calculators, and it is only a small step to understand how to apply these same techniques to matrices rather than individual numbers or varibles. In addition, by viewing MATLAB as a simple but powerful calculater, rather than as a complicated software package or computer language, you will be in the correct frame of mind to use MATLAB. You should view MATLAB as a tool that you are “playing with” — trying ideas out and seeing how

† There is a technical distinction between a command and a function in MATLAB: input arguments to commands are not enclosed in parentheses (they are separated by spaces) and there are no output arguments (i.e., a command cannot be on the right-hand side of an equal sign). In reality, this is a very ﬁne distinction since many commands can be written as functions by putting the arguments between parentheses and separating them with commas. We will generally use the terms interchangably.

3

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

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

1. Scalar Calculations

1.1. Simple Arithmetical Operations

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

ˆ

ˆ

ˆ

ˆ

ˆ

ˆ

ˆ

6

1.2. Variables

Arithmetical Operations a+b a-b a*b Addition. Subtraction. Multiplication. a/b a\b a b Division. Left division, (this is exactly the same as b/a ). Exponentiation (i.e., ab ).

ˆ

diary

Saves your input to MATLAB and most of the output to disk. This command toggles diary on and oﬀ. (If no ﬁle is given, it is saved to the ﬁle diary in the current directory.) diary on turns the diary on. diary off turns the diary oﬀ. diary <file name> saves to the named ﬁle. The up-arrow key moves backward in the MATLAB workspace, one line at a time.

↑

1.2.

Variables

Notation: We always use lowercase letters to denote scalar variables. Variables can be used to store numerical values. For example, you can store the value 21/3 in the variable x by entering >> x = 2 (1/3) This variable can then be used on the right-hand side of an equation such as >> fx = 3*x 6 - 17*x 3 + 79 There can also be more than one command on a line. For example, if you type >> x = 2 (1/3); fx = 3*x 6 - 17*x 3 + 79; g = 3/fx; then all three commands will be executed. Nothing will be printed out because semicolons follow each command. If you want everything printed out then type >> x = 2 (1/3), fx = 3*x 6 - 17*x 3 + 79, g = 3/fx Thus, you can separate statements on a line by commas or semicolons. If semicolons are used, the results of the statement are not displayed, but if commas are used, the results appear on the computer screen. Warning: A variable can be overwritten at will. For example, at present x = 21/3 . If you now type > > x = x + 5 then x becomes 21/3 + 5. No warning messages are printed if a variable is overwritten, just as in a programming language. Although we do not discuss vectors and matrices until the next section, it is important to understand that MATLAB considers scalar variables to be vectors of length one or matrices of size 1×1. For example, if you type >> fx the number 57 is returned. But you can also type >> fx(1) or >> fx(1,1) and obtain the same result. Character strings can also be stored in variables. For example, to store the string “And now for something completely diﬀerent” in a variable, enter >> str = And now for something completely different (We discuss text variables in more detail in Section 3.) Note: To put a single quote mark into the string, use two single quote marks. You can change a variable from a scalar to a vector or a matrix whenever you desire — or whenever you forget that the variable has already been deﬁned. Unlike C, for example, variables do not need to be declared (or typed). A variable springs into existence the ﬁrst time it is assigned a value, and its type depends on its context. At start-up time, MATLAB also contains some predeﬁned variables. Many of these are contained in the

ˆ

ˆ

ˆ

ˆ ˆ

ˆ ˆ

ˆ ˆ

7

1.2. Variables

table below. Probably the most useful of these is pi. Warning: Be careful since you can redeﬁne these predeﬁned variables. For example, if you type > > pi = 2 then you have redeﬁned π — and no error messages will be printed out! Another very useful predeﬁned variable is ans, which contains the last calculated value which was not stored in a variable. For example, it sometimes happens that you forget to put a value into a variable. Then MATLAB sets the expression equal to the variable ans. For example, if you type >> (3.2*17.5 - 5/3.1) 2 but then realize that you wanted to save this value, simply enter >> x = ans and x now contains (3.2 · 17.5 − 5/3.1)2 . We will discuss character strings in detail in Section 3.3. For now, >> x = Silly Walks puts the text “Silly walks” into the variable x. In MATLAB it is trivial to display a variable: simply type it. For example, if x has the value −23.6 then >> x returns

ˆ

x = -23.6000 It is sometimes useful to display the value of a variable or an expression or a character string without displaying the name of the variable or ans. This is done by using disp. For example, >> disp(x) >> disp(pi 3) >> disp( And now for something completely different ) >> disp( ------------------------------------------ ) displays -23.6000

ˆ

31.0063 And now for something completely different -----------------------------------------(The command fprintf, which will be discussed in Section 6, allows much ﬁner formatting of variables.) Note: When disp displays a variable or an array or an expression, it follows with a blank line. However, when it displays a string or a string variable, it does not. Incidentally, a valid name for a MATLAB variable is a character string containing letters (upper or lower case), digits, and underscores where the ﬁrst character must be a letter. The maximum length of a name is too long to worry about. However, there are a few names which are reserved because they have special meanings. The reserved words, called keywords, are break case catch classdef continue else elseif end for function global if otherwise parfor persistent return spmd switch try while

(Of course, you can still use End or END — but you probably shouldn’t.) Variables can also be deleted by using clear. For example, to delete x type >> clear x Warning: This is a very dangerous command because it is so easy to lose

**If you mean to type
**

> > > > clear x clear

a great deal of work.

**but instead you type
**

8

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4.2. Three-Dimensional Graphics

ezcontour, ezcontour3, ezmesh, and ezsurf. A surface can also be plotted in polar coordinates. For example, the code which plots r + e2r sin 2θ 1.2 − r cos 3θ for r ≤ 1

f (r, θ) = is

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

1 2 3

1 2 3

4 1 2 , Y = 4 3 4

5 5 5

6 6 6

7 7 7

60

4.3. Advanced Topic: Commands

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

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

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

4.3.

Advanced Topic: Commands

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

4.3. Advanced Topic: Commands

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

ˆ

ˆ ˆ

ˆ

ˆ

†

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

62

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

9. Sparse Matrices

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

119

10.1. Basic Commands

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

**10. Initial-Value Ordinary Diﬀerential Equations
**

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

where y ∈ Rn with initial condition y(t0 ) = y0 . The basic MATLAB commands are easily learned. However, the commands become more involved if we want to explore the trajectories in more detail. Thus, we divide this section into the really basic commands which are needed to generate a simple trajectory and into a more advanced section that goes into many technical details. We also provide a large number of examples, many more than in other sections of this overview, to provide a template of how to actually use the advanced features.

10.1.

Basic Commands

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

2 y2 = y1 = y = y1 (1 − βy1 ) − αy2 + Γ cos ωt

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

10.1. Basic Commands

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

† ‡

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

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

121

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Appendix: Reference Tables

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

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

159

Appendix: Reference Tables

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

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

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

160

Appendix: Reference Tables

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

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

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

quadl

161

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

10) = -5 A = A .7.diag( ones(n-1. 2 ˆ R = rand(5) [m.9. 2 ˆ 163 .-1) x = [0:30] .4) help fix or doc fix.:) A = 4*eye(n) .5 % or C = sqrt(A) A A % or mean(R(:)) b) ˆ ˆ B 2 ˆ C.7a) ˆ A = [ ones(6.ans > > (1. deg = pi/180.Solutions To Exercises These are the solutions to the exercises given in subsections 1. 2) .1751 ˆ b 2 ˆ .10.10.1) = 5. -1 ) b) 2. 4 5 6.9.2) 2.1).10. and 4.7.7.9.1i*12 20) (1/3) answer: 1.7.2*a*b*cosd(ab)) > > format long > > c answer: 6. b = 5. 5 6 7 8.4a) b) 2. A(6. 5:8. 2.5) 2. 13 14 15 16] A = [1:4.2) 1.(2*cos(th) 2 .6a) b) c) d) e) 2.1a) > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > A = [1 2 3 4. 1.5 % or B = sqrtm(A) C = A.6850e+06i ˆ ˆ > > th = input( th = ).10.2*a*b*cos(ab*deg)) + ˆ c = sqrt(a 2 ˆ 6.1a) or > > answer: b) > > > > a = 3.1). 9:12.9.1).3) 2. 3. -1 ) A = diag([1:n].9448e+01 format short e asin( (b/c)*sin(ab*deg) ) / deg c) d) 1.9.2e20 . A(1.4) zeros(6) ]. cos(2*th) . 1 ) .10.3637e+07 .diag( ones(n-1. 13:16] A = [ [1:4:13] [2:4:14] [3:4:15] [4:4:16] ] A(2. im] = max(R ) mean(mean(R)) S = sin(R) r = diag(R) A = [1 2 3.175085147187636 > > > > or > > asind( (b/c)*sind(ab) ) answer: 4. c = sqrt(a 2 + b 2 . 7 8 10] B = A . 9 10 11 12.10.diag( exp([2:n]). 2 ˆ % or x = [0:30].10.3) > > diary triangle.6.tril(A. ab = 79. .:) + A(3. 2.1) ˆ 1.10. 1 ) .diag( ones(n-1.:) = (-9/5)*A(2.

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

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

Solutions To Exercises 166 .

The octal and decimal representations of the bit patterns are shown along 167 . Dot / Forward slash 0 1 2 3 4 5 6 7 8 9 : Colon .ASCII Table ASCII Table Control Sequence Control Sequence Octal 000 001 002 003 004 005 006 007 010 011 012 013 014 015 016 017 020 021 022 023 024 025 026 027 030 031 032 033 034 035 036 037 040 041 042 043 044 045 046 047 050 051 052 053 054 055 056 057 060 061 062 063 064 065 066 067 070 071 072 073 074 075 076 077 Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 Description Null character Start of header Start of text End of text End of transmission Enquiry Acknowledgment Bell Backspace Horizontal tab Line feed Vertical tab Form feed Carriage return Shift out Shift in Data link escape Device control 1 (often XON) Device control 2 Device control 3 (often XOFF) Device control 4 Negative acknowledgement Synchronous idle End of transmissions block Cancel End of medium Substitute Escape File separator Group separator Record separator Unit separator Space ! ” Double quote # Numer sign $ Dollar sign % Percent & Ampersand ’ Closing single quote (apostrophe) ( Left parenthesis ) Right parenthesis * Asterisk + Plus sign . Comma Minus sign or dash . 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.

decimal 10 ended a line on a line printer and decimal 8 backspaced one character so that the preceding character would be overstruck. For example.ASCII Table with a description of the character symbol. The ﬁrst 32 codes (numbers 0–31 decimal) as well as the last (number 127 decimal) are non-printing characters which were initially intended to control devices or provide meta-information about data streams. ˆ 168 . 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.

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

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

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

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

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

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

Erase (a .

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

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

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

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

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

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

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

Index 182 .

- Business Economic and Managerial Decision Making
- The Mathworks_matlab Oop
- Capacity Planning
- matlab
- Matlab programming
- ar 710-2 - inventory management supply policy
- matlab70
- Matlab
- Mathematics of Evolution
- learnmatlab_sp3
- matlab
- matlab
- rial Group Theory 2nd Ed~Tqw~_darksiderg
- (eBook) - Matlab - Engineering Problem Solving
- matlab
- 9491216465StochasticGames
- matlab
- Decision Theory
- Stochastic Analysis - Classical And Quantum - T. Hida (World, 2005) WW
- Timeless Decision Theory
- Data Structures
- Operation Research As A Utility Tool
- Photo Systems
- Inventory Models
- Data Structures
- Calculus
- Polya and Szego - Problems and Theorems in Mathematical Analysis 2
- Geographic Information Systems in Transportation Research
- Quantitative Methods

Skip carousel

- tmp2059.tmp
- Aerodynamics
- Tmp 3384
- Solving Fuzzy Matrix Games Defuzzificated by Trapezoidal Parabolic Fuzzy Numbers
- tmp65C0.tmp
- UT Dallas Syllabus for math2333.502.07s taught by Paul Stanford (phs031000)
- tmp51FA.tmp
- tmp939A.tmp
- Modeling To Predict Cutting Force And Surface Roughness of Metal Matrix Composite Using ANN
- AHP technique a way to show preferences amongst alternatives
- UT Dallas Syllabus for math2333.001.10s taught by (axe031000)
- tmp4D3F.tmp
- tmp9363.tmp
- UT Dallas Syllabus for math6319.501 05f taught by Viswanath Ramakrishna (vish)
- Diacetyl and acetyl propionyl testing on Suicide Bunny (Sucker Punch and Mother's Milk)
- UT Dallas Syllabus for math2418.001.08f taught by (xxx)
- Computer Oriented Numerical Methods
- tmp9649.tmp
- bls_2086_1981_v1.pdf
- UT Dallas Syllabus for math2333.503.10s taught by Paul Stanford (phs031000)
- UT Dallas Syllabus for math2418.001.07s taught by Paul Stanford (phs031000)
- tmpCA93.tmp
- tmpED85.tmp
- tmp8BC6
- tmpA453.tmp
- Tmp 3008
- De Acc Aprltr 2015b
- UT Dallas Syllabus for math2333.501.08s taught by Paul Stanford (phs031000)
- tmpD29D.tmp
- UT Dallas Syllabus for math2418.001.07f taught by Paul Stanford (phs031000)

- Lighting.pdf
- 2008 11 25 Methods Method Biological 1687-Bio
- EN12464-2011.pdf.pdf
- 365-12_IVMS
- Checklist for Maintenance of Safety Equipment
- 17025 Presentation
- gpcl_trs957_annex1
- Introduction to the IES Handbook PDF.pdf
- 201412081129-NABL-122-03-doc
- 11D-InterlaboratoryComparisonsandProficiencyTesting
- 2008_11_25_methods_method_biological_1687-bio.pdf
- 6H-17025AccreditationSystem
- 17 Rautiainen Quality System in Turku PET Centre
- E83.22166.pdf
- Laboratory-Ventilation-Codes-and-Standards--Application-Guide_A6V10324363_us-en.pdf
- FluoroMax P
- NFPA_14-2010
- IOM.pdf
- boat safety codes
- Full Text 01
- EPA600-R-12-555 SAM 2012
- Kuwait Epa Act 210- Year 2001
- USEPA method 6010c
- Checklist_for_Maintenance_of_Safety_Equipment.pdf
- PHSE-13-P02 - Occupational Exposure Management

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?

Close Dialog## This title now requires a credit

Use one of your book credits to continue reading from where you left off, or restart the preview.

Loading