introduction to matlab - university of new mexicowilliams/cs530/matlab4_folie.pp4.pdfmatlab is a...

75
Introduction to MATLAB Aaron Lahman Chris Ellison May 5, 2003

Upload: others

Post on 28-Aug-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Introduction to MATLAB

Aaron Lahman Chris Ellison

May 5, 2003

Page 2: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Contents

1 Introduction 1

1.1 Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 Evaluations and “ans” . . . . . . . . . . . . . . . . . . . . . . . . 1

1.3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.4 Output Suppression . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.5 Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.6 Workspace Window . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.8 Exploration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Matrices 7

2.1 Background Information . . . . . . . . . . . . . . . . . . . . . . . 7

2.2 Inputting Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.3 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.4 Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.6 Division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.8 Exploration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3 Arrays and Basic Plotting 19

3.1 Matrices as Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3.2 Basic Array Constructors . . . . . . . . . . . . . . . . . . . . . . 20

3.3 Array Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3.4 Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3.5 3D Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3.6 Multiple Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

3.7 Multiple Plots on the Same Figure . . . . . . . . . . . . . . . . . 25

3.8 Zoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3.10 Exploration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

i

Page 3: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

ii CONTENTS

4 M-Files 27

4.1 File Viewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.2 New Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.3 Format of an M-File . . . . . . . . . . . . . . . . . . . . . . . . . 284.4 Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.5 Multiple Return Values . . . . . . . . . . . . . . . . . . . . . . . 304.6 Exploration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

5 Flow Control 33

5.1 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . 335.2 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.3 While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.4 For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365.5 If, Elseif, and Else . . . . . . . . . . . . . . . . . . . . . . . . . . 365.6 Iterative Problem Solving . . . . . . . . . . . . . . . . . . . . . . 375.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415.8 Exploration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

6 Advanced Plotting 43

6.1 Surface Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436.2 Color Maps and Pcolor . . . . . . . . . . . . . . . . . . . . . . . . 446.3 Subplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476.4 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476.5 Title Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516.6 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536.8 Exploration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

7 Animations 55

7.1 Opening a Movie File for Output . . . . . . . . . . . . . . . . . . 557.2 Adding Frames to the Movie . . . . . . . . . . . . . . . . . . . . 567.3 Closing the Movie File . . . . . . . . . . . . . . . . . . . . . . . . 567.4 M-Files that Produce Animation Files . . . . . . . . . . . . . . . 597.5 Exploration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

8 The End 63

A Exploration Answers 65

A.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65A.2 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66A.3 Arrays and Basic Plotting . . . . . . . . . . . . . . . . . . . . . . 66A.4 M-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66A.5 Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66A.6 Advanced Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . 66

Page 4: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 1

Introduction

MATLAB is a numerical package geared toward engineering applications, espe-cially those which make heavy use of matrix mathematics. In this section, youwill be instructed on the basic operations of the MATLAB User Interface, or UI.MATLAB is very flexible in providing most of its tools through a Graphical UserInterface, or GUI, and a Command Line User Interface, or CLUI.

1.1 Command Line

MATLAB opens to a window with three panes, the largest on the right beingthe CLUI, titled ”Command Window”. You should see the text in Figure 1.1.

The double arrows ( >> ) indicate the command prompt. When this appearsat the end of the CLUI, MATLAB is indicating that it is ready to accept instruc-tion. Every MATLAB command is implemented as a programming function.Soon you will be able to write programs that utilize these functions.

1.2 Evaluations and “ans”

Within the Command Window, the user can perform basic calculations by eval-uating mathematical expressions. MATLAB supports most common math func-tions, such as those seen in Figure 1.2.

To get started, select "MATLAB Help" from the Help menu.

>>

Figure 1.1: The Command Window.

1

Page 5: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

2 Lesson 1: Introduction

+ - * / ^

log() log10() log2()

sin() cos() tan()

pi exp() sqrt()

Figure 1.2: Some common MATLAB functions.

MATLAB has many more functions as well. For detailed explanations ofthese functions, see Section 1.7 at the end of this lesson. For now, input thecode found in Figure 1.3, and press enter when finished.

>> 2 + 2

Figure 1.3: The input code for the CLUI output in Figure 1.4.

The CLUI output can be found in Figure 1.4.

ans =

4

Figure 1.4: The CLUI output for the code in Figure 1.3.

1.3 Variables

Variables, in math, are unknown quantities. In computer science, they are stor-age locations for temporary data. The information stored is always a specific,modifiable set of binary data or a specific, modifiable number. Often, program-mers will refer to stored data as boxes. Thus, whenever a programmer refers toa box, it should be clear that they are really referring to the information storedwithin it.

The reader may have noticed that the output for the previous example wasan equality, ans = 4. Every time an expression is entered, MATLAB will storethe result in a variable. If no variable is specified, then MATLAB will store theresult in the variable ans. It is also possible to use variables within expressions.Continuing the last example, the reader can input the code shown in Figure 1.5and compare the output. Continuing the same operation will yield results of 8,10, 12, 14, 16, 18. . .

Page 6: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 1: Introduction 3

>> ans + 2

ans =

6

Figure 1.5: Sample code demonstrating how to use variables within expres-sions.

To perform an assignment, enter the variable name, an equal sign, and thenan expression. Variable names must start with a letter, and can be made upof letters, numbers, and the underscore symbol ( ). See Figure 1.6 for anexample.

>> whole = 10

whole =

10

>> whole2half = whole / 2

whole2half =

5

Figure 1.6: Sample code demonstrating how to perform an assignment.

1.4 Output Suppression

MATLAB prints the results of every expression by default. To save space,output can be suppressed by ending an expression with a semicolon ( ; ). ThenMATLAB will evaluate the expression, storing the result in a specified variableor in the variable ans. It will not display the results of the expression. SeeFigure 1.7 for a demonstration.

>> suppressMe = 1;

>>

Figure 1.7: Sample code demonstrating how to suppress output.

Page 7: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

4 Lesson 1: Introduction

1.5 Cache

The reader may have already noticed the function of the cache window, titled“Command History.” To the lower left side of the MATLAB window, there isa window pane that records all previously entered expressions. To re-evaluatean expression, double-click on a particular expression within the cache, andMATLAB will enter the input into the CLUI and evaluate it.

Be careful! Even though the text of the expression is identical to a previousexpression, the result might be different. This is usually true for expressions in-volving variables. If the value of a variable has changed since the expression wasfirst evaluated, then it is very likely that future evaluations will yield differentresults. This concept was demonstrated with Figure 1.5 since the current valueof ans depended upon the previous value of ans. Thus, repeated evaluationsgave different results every time.

Another method for recalling previous commands is to press the up-arrowwhile at the command line. One at a time, this will recall expressions from the“Command History” and display them without evaluating them.

Try typing in a partial expression, and then press up. MATLAB will onlyrecall those expressions that match the partial expression. For example, type“100 + 100” and then hit return. Then, type the partial expression “100 +”and press up. Immediately, MATLAB will recall “100 + 100” since there wasan expression in the command history that matched the partial expression.During this process, pressing down will go forward through the history; this isuseful especially if one has pressed up too many times.

1.6 Workspace Window

The workspace window is located in the upper left-hand window pane of MAT-LAB. This window lists all the variables that have been created from the com-mand line. By double clicking on a variable listed, you can edit its value or size(if the variable is a matrix).

1.7 Summary

This lesson has covered the basics of operating MATLAB and its command lineenvironment. Table 1.1 is a summary of the commands covered so far and a fewothers (all angles are in radians). Let m and n be variables; numbers shouldreplace them when performing evaluations. For more detailed information aboutthese commands, consult the MATLAB help files. Use them, and use them often.

Page 8: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 1: Introduction 5

m + n Additionm - n Subtractionm * n Multiplicationm / n Divisionm ^ n Powersqrt(m) Square Rootlog10(m) Base-10 Logarithmlog2(m) Base-2 Logarithmlog(m) Natural Logarithm (Base-e)exp(m) Exponential (em)pi The constant pii Constant defined by sqrt(-1)

j Constant defined by sqrt(-1)

sin(m) Sine of an anglecos(m) Cosine of an angletan(m) Tangent of an angleasin(m) Inverse sine of an angleacos(m) Inverse cosine of an angleatan(m) Inverse tangent of an anglesinh(m) Hyperbolic sine of an anglecosh(m) Hyperbolic cosine of an angletanh(m) Hyperbolic tangent of an angleasinh(m) Inverse hyperbolic sine of an angleacosh(m) Inverse hyperbolic cosine of an angleatanh(m) Inverse hyperbolic tangent of an angle

Table 1.1: A summary of the commands covered in Lesson 1. The variables mand n represent numbers. All angles are specified in radians.

1.8 Exploration

Using MATLAB as a calculator, determine the magnitude of the normal force ona 200 kg block at rest on a 20◦ incline. Assume that gravitational acceleration is9.8 m/s2. Try inputting these constants as variables so that you can write yourfinal equation in terms of variables rather than numbers. Remember, MATLABuses radians for its trigonometric functions, not degrees.

Page 9: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make
Page 10: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 2

Matrices

This section provides an introduction to matrices and the operations that ma-nipulate them. Beginning with constructors, this lesson will cover topics such asaddition, multiplication, transposing, inversing, determinants, and lastly, ma-trix ”division.” It is assumed that the reader has gone through Lesson 1.

2.1 Background Information

A matrix is a rectangular arrangement of data usually consisting of numbers.To describe their size, matrices are divided into rows and columns. A matrixwith m rows and n columns is said to be an m-by-n matrix (also known as anm × n matrix). For example,

[a1,1 a1,2 a1,3

a2,1 a2,2 a2,3

]

is representative of a 2 × 3 matrix.

Notice that every element has a coordinate associated with it. The upperleft-hand corner of the matrix is usually assigned the coordinate (1, 1). Forexample, a2,3 represents the element at the second row and third column.

2.2 Inputting Matrices

To input a matrix into MATLAB, the user can separate the columns by commasand the rows by semicolons. Figure 2.1 shows how to input a 2 × 3 matrix.Figure 2.2 shows an alternative way to input the same matrix. In the alternativeway, each line represents a new row. Be careful to input a value for every elementin the matrix, otherwise MATLAB will return an error (see Figure 2.3).

There are many other useful types of matrices, but three stand out in partic-ular: row vectors, column vectors, and scalars. A row vector is an m×1 matrix,

7

Page 11: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

8 Lesson 2: Matrices

>> matrix = [ 13 1 20; 18 9 24 ]

matrix =

13 1 20

18 9 24

Figure 2.1: The command to input a 2 × 3 matrix. This method uses semi-colons and commas to separate the rows and columns.

>> matrix = [ 13, 1, 20

18, 9, 24 ]

matrix =

13 1 20

18 9 24

Figure 2.2: An alternative way to input a 2 × 3 matrix. This method usesseparate lines to represent the rows.

>> matrixError = [ 1 2 3; 4 5 ]

??? Error using ==> vertcat

All rows in the bracketed expression must have the same

number of columns.

Figure 2.3: MATLAB will return an error if the matrix is input incorrectly.The rows must always have the same number of columns.

Page 12: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 2: Matrices 9

>> rowVector = [ 1 2 3 ]

rowVector =

1 2 3

>> columnVector = [ 1; 2; 3 ]

columnVector =

1

2

3

>> scalar = [ 1 ]

scalar =

1

>> scalar = 1

scalar =

1

Figure 2.4: An example of a row vector, column vector, and scalar. Noticethat scalar matrices are equivalent to setting a variable equal to anumber (as in Lesson 1).

and a column vector is a 1 × n matrix. A scalar, of course, is a 1 × 1 matrix.Inputting a 1 × 1 matrix is equivalent to setting a variable equal to a number.Examples of these matrices can be found in Figure 2.4.

2.3 Operators

Matrix addition closely follows regular addition; the same is true for subtraction.To add, just add the matricies’ corresponding elements. However, matrices mustbe of equal size in order to add and subtract them. To add matrices in MATLAB,use the regular addition sign. To subtract, use the regular subtraction sign.Equation 2.1 is an example of how matrix addition works.

Page 13: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

10 Lesson 2: Matrices

[a b cd e f

]

+

[g h ij k `

]

=

[a + g b + h c + id + j e + k f + `

]

(2.1)

Matrix multiplication is somewhat more complicated. First of all, matricescan only be multiplied if their inner matrix dimensions agree. That is, an m×nmatrix can only by multiplied by an n×q matrix (where m, n, and q are positivewhole numbers). The matrix product is an m × q. Further, it should be notedthat matrix multiplication, in general, does not commuate. That is, for matricesM and N , MN 6= NM .

To illustrate matrix multiplication, see Equation 2.2. Try and discover aprocedure that can be generalized for matrices of any size. In the example,notice that the 2 from the 3 × 2 matrix matches the 2 from the 2 × 3 matrix.This means that multiplication is possible. Also, notice the size of the resultantmatrix. The 3’s come the outer matrix dimensions. produce it! For a moredetailed discussion about matrices, consult your favorite math book.

a bc de f

︸ ︷︷ ︸

3×2

[g h ij k `

]

︸ ︷︷ ︸

2×3

=

ag + bj ah + bk ai + b`cg + dj ch + dk ci + d`eg + fj eh + fk ei + f`

︸ ︷︷ ︸

3×3

(2.2)

Examples of these all these operations can be found in Figure 2.5.

2.4 Constructors

In some situations, it is useful to create a matrix full of zeros. In other situations,a matrix full of ones is equally useful. Yet again, other situations might requirea matrix with ones down the diagonal. The diagonal of a square matrix includesall the elements from the upper left-hand corner to the lower right-hand corner.

To construct a matrix full of zeros, use the zeros command. As arguments,if only one argument is specified, then the zeros command will create a squarematrix. For example, zeros(m) will create an m-by-m matrix full of zeros. Onthe other hand, zeros(m,n) will create a m-by-n matrix full of zeros. As analternative input, one can also use the command zeros([m n]).

The size command will return the size of a matrix in the form of a row vec-tor. Thus if given a matrix A, a zero matrix of the same size can be constructedwith the following command: zeros(size(A)).

To construct a matrix full of ones, use the ones command. Its argumentsfollow the same syntax as the zeros command. To construct a matrix with onesalong the diagonal, use the eye command. The command’s name eye is meantto serve as a reminder of the “identity matrix.” A matrix with ones along thediagonal is known as an identity matrix. The arguments given for the zeros

command will also work for the eye command. Examples of all three of thesecommands can be found in Figure 2.6.

Page 14: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 2: Matrices 11

>> A = [1 2; 3 4; 5 6], B = [1 2 3 4; 2 4 6 8], C=B;

A =

1 2

3 4

5 6

B =

1 2 3 4

2 4 6 8

>> A + B

??? Error using ==> +

Matrix dimensions must agree.

>> A * B

ans =

5 10 15 20

11 22 33 44

17 34 51 68

>> B + C, B - C

ans =

2 4 6 8

4 8 12 16

ans =

0 0 0 0

0 0 0 0

>> B * C

??? Error using ==> *

Inner matrix dimensions must agree.

Figure 2.5: Sample code demonstrating matrix operators.

Page 15: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

12 Lesson 2: Matrices

>> zerosMatrix = zeros([ 2 3 ])

zerosMatrix =

0 0 0

0 0 0

>> onesMatrix = ones(3)

onesMatrix =

1 1 1

1 1 1

1 1 1

>> eyeMatrix = eye( size(onesMatrix) )

eyeMatrix =

1 0 0

0 1 0

0 0 1

Figure 2.6: Sample code demonstrating how to create matrices full of zeros,ones, or just ones along the diagonal.

2.5 Functions

MATLAB provides many matrix functions. Only some of them will be intro-duced in this section. The first is the transpose function. It takes the rowsof the input matrix and transposes them into columns for the output matrix.Figure 2.7 shows how to execute this command.

The next function calculates a matrix’s determinant. The determinant, fora 2 × 2 matrix, is given by:

|A| = det(A) = det

([a bc d

])

= ad − bc

MATLAB computes determinants for all square matrices using Gaussianelimination. Remember, determinants can only be computed for square ma-trices; a square matrix has dimensions m × m. An example how to use thedeterminant function can be seen in Figure 2.8.

Page 16: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 2: Matrices 13

>> A = [ 1 2; 3 4]

A =

1 2

3 4

>> transposeA = A’

transposeA =

1 3

2 4

Figure 2.7: Sample code demonstrating how to transpose a matrix.

Another very important command computes the inverse of a matrix. Amatrix is said to be invertible (or nonsingular) if, and only if, the determinantis nonzero. Again, discussion of inverses and determinants requires that thematrix be square. If M is nonsingular,then the inverse of M is denoted by M−1.A matrix and its inverse are related in such a way that MM−1 = I = M−1M .In other words, the product of M and M−1, in any order, is equal to the identitymatrix. Figure 2.9 shows how to use the inverse command in MATLAB.

The diagonal of a matrix was briefly discussed in Section 2.4 and will beexpanded upon here. In general, the elements considered part of the diagonalinclude all those elements whose coordinates are of the form (m,m).

In the example below, only a1,1, a2,2 would be included in the diagonal.

[a1,1 a1,2 a1,3

a2,1 a2,2 a2,3

]

MATLAB provides a function that will return a column vector whose ele-ments are the diagonal elements of the inputted matrix; it is called diag. Ifthese elements are summed, then a quantity known as the trace, will have beencomputed. MATLAB also provides a trace function.

The trace function makes use of another matrix function called sum. If thesum function is passed a matrix, it will sum all the elements along the columnsand then, return a row vector. If the sum function is passed a row or columnvector, then it will return the the sum of the elements within those vectors.With this function, we can see that the trace function is simply the sum of thediagonal elements of a matrix. This can be seen in Figure 2.10.

Page 17: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

14 Lesson 2: Matrices

>> A = [ 1 2 3

0 pi exp(1)

-50 -40 -30 ]

A =

1.0000 2.0000 3.0000

0 3.1416 2.7183

-50.0000 -40.0000 -30.0000

>> det(A)

ans =

213.8942

>> det(A’)

ans =

213.8942

>> det( [1 1 1; 2 2 2] )

??? Error using ==> det

Matrix must be square.

Figure 2.8: Sample code demonstrating how to compute the determinant of asquare matrix. Notice that the determinant of a matrix is equalto the determinant of the transposed matrix. In the last line ofcode, MATLAB gave an error because the matrix was not square.

Page 18: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 2: Matrices 15

>> A = [ 1 2; 3 4]

A =

1 2

3 4

>> inv(A)

ans =

-2.0000 1.0000

1.5000 -0.5000

>> A * inv(A)

ans =

1.0000 0

0.0000 1.0000

>> inv([ 1 1; 1 1])

Warning: Matrix is singular to working precision.

(Type "warning off MATLAB:singularMatrix"

to suppress this warning.)

ans =

Inf Inf

Inf Inf

Figure 2.9: Sample code demonstrating how to compute the inverse of a squarematrix. Notice that the matrix and its inverse multplied in sucha way to produce the identity matrix. In the last line of code,the matrix was singular (meaning that the determinant was zero).Therefore, MATLAB could not compute an inverse.

Page 19: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

16 Lesson 2: Matrices

>> A = [ 1 2 3; 4 5 6 ]

A =

1 2 3

4 5 6

>> sum(A)

ans =

5 7 9

>> sum(sum(A))

ans =

21

>> diag(A)

ans =

1

5

>> sum(diag(A))

ans =

6

>> trace(A)

ans =

6

Figure 2.10: Sample code demonstrating the sum, diag, and trace functions.Notice that the sum of the diagonal of A was equal to the traceof A. Further, notice that the sum of all the elements of A werecomputed with a double sum.

Page 20: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 2: Matrices 17

2.6 Division

Matrix “division” is very closely related to the idea of inverses and linear sys-tems. If the reader has not had prior experience with linear systems, read thissection and try to remember it. It will become useful in the future. To thosereaders with experience, matrix divions is often broken into two categories: leftand right division.

Consider the linear system: Ax = B. If A is square and invertible, thenthe MATLAB command A\B can be thought of as inv(A)*B. The reader shouldrecognize this as the solution to the linear system.

A−1Ax = A−1B Multiplying both sides on the left by A−1

x = A−1B

In general, A might not be a square matrix, and thus, it will not have aninverse. This is slightly more complicated situation, and the text would notbenefit from its discussion. Please refer to the MATLAB help files for moreinformation.

Lastly, right division, A/B is about the same as B*inv(A). To be more precise,it is the transpose of A′\B′. That is, A/B = (A′\B′)′.

2.7 Summary

This section has covered the basics of matrices and some of the commands tomanipulate them. Table 2.1 summarizes the commands covered in this sectionand includes a couple more. Let m and n be numbers, and let Q and R bematrices. For more detailed information about these commands, consult theMATLAB help files. Use them, and use them often.

2.8 Exploration

While not a mathematical proof, it is often helpful to verify certain propertiesof matrices. Just for fun, try to verify the following properties.

inv(A*B) = inv(B) * inv(A)

det(A*B) = det(A) * det(B)

det(A) = det(A’)

det(inv(A)) = inv(det(A))

diag(A) = diag(A’)

trace(A) = trace(A’)

trace(A*B) = trace(B*A)

trace(A+B) = trace(A) + trace(B)

Page 21: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

18 Lesson 2: Matrices

Q + R Matrix AdditionQ - R Matrix SubtractionQ * R Matrix MultiplicationQ ^ m Matrix Power (multiply Q to itself m times)Q \ R Matrix Left DivisionQ / R Matrix Right DivisonQ(m,n) Returns the element located at (m,n).zeros(m) Creates an m × m matrix of zeros.zeros([m n]) Creates an m × n matrix of zeros.ones(m) Creates an m × m matrix of ones.ones([m n]) Creates an m × n matrix of ones.eye(m) Creates an m × m identity matrix.eye([m n]) Creates an m × n identity matrix.size(Q) Returns a row vector representing the dimensions of Q.Q’ Returns the transpose of Q.det(Q) Computes the determinant of Q.inv(Q) Provided Q is invertible, returns the inverse of Q.diag(Q) Returns the diagonal elements of Q as a column vector.sum(Q) If Q is a matrix, it returns a row vector containing

the sums of Q’s columns. If Q is a row or columnvector, it returns the sum of the elements.

trace(Q) Returns the trace of Qpoly(Q) If Q is square, it returns a row vector with elements

representing the coefficients of the characteristicpolynomial det(sI-Q).

roots(Q) Returns a column vector whose elements are the rootsof the row vector Q. The elements of Q representthe coefficients of a polynomial.

Table 2.1: A summary of the commands covered in Lesson 2. The variables mand n represent number; Q and R represent matrices.

Page 22: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 3

Arrays and Basic Plotting

This section introduces arrays and basic plotting techniques.

3.1 Matrices as Lists

In MATLAB, matrices can also function as arrays. One of the major advantagesof arrays is that they allow operations to be performed on many numbers atonce. For example, an array would allow one to compute the value of a functionat multiple points simultaneously. To input an array of numbers, one only needsto input a 1× n matrix (a row vector). Figure 3.1 shows how to input an arraycontaining the numbers 1, 2, and 3.

>> a = [1, 2, 3]

a =

1 2 3

>> a = [1 2 3]

a =

1 2 3

Figure 3.1: Sample code demonstrating two ways to input an array.

19

Page 23: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

20 Lesson 3: Arrays and Basic Plotting

3.2 Basic Array Constructors

Also, MATLAB includes built in functions for generating commonly used arrays.For instance, the colon operator can be used to construct an array of countingnumbers. Figure 3.2 shows an example of how to generate the array of numbers0 through 9.

>> [0:9]

ans =

0 1 2 3 4 5 6 7 8 9

>> (0:9)

ans =

0 1 2 3 4 5 6 7 8 9

>> 0:9

ans =

0 1 2 3 4 5 6 7 8 9

Figure 3.2: Sample code demonstrating the various ways to input an array ofnumbers using the colon operator.

Also, arrays can be constructed by specifying the a step size. For instance,Figure 3.3 shows how to construct all tenth intervals between 0 and 1.

3.3 Array Calculations

To perform calculations with arrays, MATLAB requires a different notation tobe used for multiplication, division, and powers. For multiplication, divisionand powers, the user must place a period before the operator. If the userfails to change notation, MATLAB might misunderstand the instruction, andinterpret the command as a matrix operation. Executing such commands oftengive incorrect outputs and errors. When multiplying an array by a scalar, it isnot necessary to precede the operator with a period. Figure 3.4 illustrates someof these concepts.

Page 24: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 3: Arrays and Basic Plotting 21

>> 0:0.1:1

ans =

Columns 1 through 6

0 0.1000 0.2000 0.3000 0.4000 0.5000

Columns 7 through 11

0.6000 0.7000 0.8000 0.9000 1.0000

Figure 3.3: Sample code demonstrating how to create an array of numbersbetween 0 and 1 at one-tenth intervals.

>> [1 2] * [3 4]

??? Error using ==> *

Inner matrix dimensions must agree.

>> [1 2] .* [3 4]

ans =

3 8

>> [1 2] * 4

ans =

4 8

>> [1 2] .* 4

ans =

4 8

Figure 3.4: Sample code demonstrating how and how not to perform calcula-tions involving arrays.

Page 25: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

22 Lesson 3: Arrays and Basic Plotting

>> x = 0:0.1:10;

>> y = 10 + x .^ 2;

>> plot(x,y);

Figure 3.5: Sample code demonstrating the plot command.

3.4 Plot

Now, the reader will learn to plot the relationship between two arrays of data.This procedure will build upon the techniques described in the previous sec-tions. First, assign the list of numbers 0 through 10, at one tenth intervals,to the variable x. Then, assign 10 plus the square of x to the variable y. Re-member to use the array power function (and not the normal power function).Lastly, plot the relationship between x and y. Do this with the following com-mand: plot(x,y). Since these arrays might be long, it would be helpful tosuppress the output (see Section 1.7). To verify the code, see Figure 3.5.

A graph should appear on the screen, after the plot command, in a separatewindow. This window is called a “figure.” The menus provide useful tools,such as the save, export and print commands. The save command is especiallyimportant since it provides the opportunity for later viewing and editing. Themenu also provides tools to change the scales of the axes, to label parts of thefigure, and to calculate polynomial approximations of the graph.

To change the major parts of the graph (such as the axes or line color),the reader must enter edit mode. From the “Tools” menu, select “Edit Plot.”Simultaneously, the reader should notice a button depressing. This button hasthe mouse cursor icon on it, and can also be used to enter edit mode.

Now, double-click upon an object within the figure, and a “Property Editor”window will appear. This window contains many options that allow the readerto configure the double-clicked object.

While in edit mode, the reader can change the y-axis from a linear scale intoa logarithmic scale. First, double-click upon the y-axis. In the window thatappears, click the “Y” tab located near the top of the “Property Editor” window.Now the reader should locate where it says “Scale:” and then select “Log.” Ifthe “Immediate apply” box is checked, the changes will be seen immediately.Clicking the “OK” button, will close the window. If done correctly, the graphwill have a logarithmic scale on the y-axis.

3.5 3D Plotting

Another useful tool is the plot3 command; it will plot three arrays in threedimensions. For example, to plot a spiral, use the code in Figure 3.6.

Page 26: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 3: Arrays and Basic Plotting 23

>> x = 0:0.1:10;

>> y = sin(x);

>> z = cos(x);

>> plot3(x,y,z);

Figure 3.6: Sample code demonstrating the plot3 command.

It is important to use the graph rotation mode when dealing with threedimensional graphs. To do this, select “Rotate 3D” from the “Tools” menu.Again, a button with a rotation icon will depress simultaneously. To rotate,click and hold the mouse button anywhere on the graph. Now, drag the mouseand the reader should notice ‘virtual box’ as the mouse is moved around. Uponreleasing the mouse button, the graph will re-plot at the new viewing angle.

It is often useful to see the grid-lines of 3D graphs. This is done to showperspective. To do this, enter edit mode and double click on an axis. Undereach axis tab, select “Grid: Show.” For example, click the “X” tab and select“Grid: Show.” Repeat this for the “Y” and “Z” tabs. Then click the “OK”button, and grid-lines will appear drawn on the ‘walls’ of the plot. This willhelp to visualize the viewing angle.

Alternatively, one could instruct MATLAB to show only the outline of the‘virtual box.’ Enter edit mode and double-click an axis. Select the “Style”tab, and click the “On” check-box that is next to “Axes box.” Click the “OK”button when finished.

3.6 Multiple Plots

The reader may have noticed that the plot command places new plots in thesame figure as old plots. To create a new figure, simply type figure. To createa new figure with a name, the command is figure(’name’,’NAME’), whereNAME is the name of the figure.

When a figure is created, a reference is assigned to it. For example, the firstfigure window to appear says “Figure No. 1” If the user were to create a secondfigure with the name ’Bob’, then the window would say: “Figure No. 2: Bob”in the title bar. Good programming would assign a variable to the figure; then,that the variable would represent the figure reference.

When plotting, MATLAB will always plot to the active figure. To changethe active figure, type figure(ref) where ref represents the figure reference.Alternatively, one could activate a figure by opening its window and then re-turning back to MATLAB. Examples of all of these commands can be found inFigure 3.7.

Page 27: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

24 Lesson 3: Arrays and Basic Plotting

>> figure;

>> myFigure1 = figure(’name’,’Bob1’)

myFigure1 =

2

>> myFigure2 = figure(’name’,’Bob2’)

myFigure2 =

3

>> figure(myFigure1)

>> plot(1:10)

Figure 3.7: Sample code demonstrating how to create a new figure. The firstcommand creates a figure but does not assign a variable to itsreference. The second and third commands, however, do assignvariables to the figure reference. The fourth command activatesthe figure referenced by myFigure1. Thus, the fifth command willdisplay on the figure referenced by myFigure1.

Page 28: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 3: Arrays and Basic Plotting 25

3.7 Multiple Plots on the Same Figure

Instead of creating a separate figure, it is also possible to keep adding plots ontothe same graph. To do this, enter the command hold on. To leave this mode,type the command hold off. Hold means to hold the graph data as it stands.When hold is on, every plot command will add more data to the present graph,each having separate properties that can be edited. When hold is turned off, theplot command will clear the graph before adding the new data. The immediateresult is that only one set of data is displayed at a time.

3.8 Zoom

It may be useful to zoom in on portions of the graph. To do so, select “ZoomIn” from the “Tools” menu. Then single-clicks on the graph will either zoomin about the clicked point. A double-click will return the graph to its originalzoom. Also, a single-click and drag will create a “zoom box”. Upon releasing,MATLAB will replot and set the axes to zoom on the data within the “zoombox”. To zoom out, select “Zoom Out” from the “Tools” menu. Notice thatMATLAB will only allow the user to zoom out from a previously zoomed inposition. Thus, one cannot zoom out from the original zoom. Both the zoomin and zoom out options are also available as buttons in the figure toolbar.

3.9 Summary

This lesson has covered the basics of arrays and plotting. Table 3.1 is a summaryof the commands covered in this lesson. Let p, q, and r be arrays. For moredetailed information about these commands, consult the MATLAB help files.Use them, and use them often.

3.10 Exploration

A person named Picka Degreenow is seeking to throw a ball forward as faraway as possible. Determine the optimum angle to throw the ball by plottingthe various projectile trajectories. Assume that only the gravitational force ispresent and that the gravitational constant is 10 m/s

2. Also, assume that Picka

Degreenow is throwing the ball from ground level with an initial velocity of5 m/s.

Hint: Create a time array from 0 to 2 seconds. Then derive the formulas forthe x- and y-position. Begin plotting at 0◦ and move up in increments of 15◦.The optimum angle will be on one of those intervals (and it is less than 90◦).Then use the zoom feature to determine the optimum angle.

Page 29: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

26 Lesson 3: Arrays and Basic Plotting

x:y:z Creates an array with first element x,incrementing by y, ending at z.

p(m) Returns the mth element of p.plot(p,q) Plots p versus q in the active figure.plot3(p,q,r) Plots p, q, and r in the active figure.figure Creates and activates a new figure.figure(’name’,’NAME’) Creates a new figure named NAME.figure(figRef) Activates the figure referenced by figRef.hold on On next plot, holds the current plot.hold off On next plot, erases the current plot.

Table 3.1: A summary of the commands covered in Lesson 3. The variables p,q, and r represent arrays; x, y, and z represent numbers.

Page 30: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 4

M-Files

This section introduces M-Files through an example. The reader should gothrough the lesson on matrices before proceeding.

4.1 File Viewer

The reader may have noticed a second tab in the “Workspace” window (thewindow that displays current variables). Underneath the window are two tabs:”Workspace” and ”Current Directory”. Select the “Current Directory” tab; itprovides a window that allows the user to navigate the computer’s folders ina way similar to that of Windows Explorer. The current directory is whereMATLAB saves and reads every file.

4.2 New Files

Using the ”Current Directory” window, navigate to a directory appropriatefor saving programming files. The user can also create new directories withthis browser by clicking on the new folder button. The new folder button is apicture of a closed folder with a sparkle in the upper right (it is right next tothe binoculars). Upon pressing the new folder button, the user will see a newdirectory pop up within the current directory. Type in a name and press enter.

To create an M-File, click on the “File” menu, select “New”, and then,select “M-File”. A window will pop up; it is the M-File Editor. From the “File”menu, select “Save As...”. Then navigate to the programming directory chosenearlier, and save the file with the name “foo.m”. After closing the M-File,one can always reopen that file by double-clicking it while within the “CurrentDirectory” window.

An M-File can be as simple as a list of commands needing evaluation. Everycommand that can be input into the CLUI, can also be placed within an M-File.

27

Page 31: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

28 Lesson 4: M-Files

The advantage of this, is that parameters can be changed without retyping everycommand. However, an M-File can also be more complex. It can implement auseful “function”. The next few sections will demonstrate how to use M-Filesto implement functions.

4.3 Format of an M-File

For those with little programming experience, a function is a small programthat accomplishes one set tasks. For instance, sqrt is a function. When given avariable, the computer passes it to the sqrt function. Then, the sqrt functionwill perform calculations on the variable to determine its square root. Whenthe function finishes, it returns the result back to the user.

As an example, the square root function will be reimplemented. Open thefile “foo.m” that was created in Section 4.2, and copy into it the text fromFigure 4.1.

function [ y ] = foo( x )

%foo Performs square root.

% Input: an m-by-n matrix

% Output: an m-by-n matrix

% whose elements are the square

% roots of the elements of x

y = exp( 0.5 * log( x ) );

Figure 4.1: Sample code to re-implement the square root function.

In the first line of code, the reader should see that “foo” appeared withinthe source code. All functions in MATLAB must be contained in their own file,and that file must have same name as the function.1 In the parenthesis, thereader should also see an ”x”. This is the function’s input variable. A functioncan have more than one input variable, but they must be separated by commas.Preceding “foo”, the reader should see a “y” in brackets. This is the function’sreturn variable. A function can also have more than one return variable, butthey too, must be separated by commas.

Every M-File must begin with the word “function” in order to specify thata function is being written. Keep in mind that a function need not have inputor output variables.

The next line of code is a comment. In MATLAB, a comment is initiatedwith a % symbol, and it continues through the end of the line. Usually, the first

1Private functions are the exception to this rule. A private function is a function used only

within another function. However, private functions are beyond the scope of this lesson. See

the MATLAB help files for further reference.

Page 32: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 4: M-Files 29

>> help foo

foo Performs square root.

Input: an m-by-n matrix

Output: an m-by-n matrix

whose elements are the square

roots of the elements of x

>> xSquared = (1:5) .^ 2

xSquared =

1 4 9 16 25

>> x = foo(xSquared)

x =

1 2 3 4 5

Figure 4.2: Sample code demonstrating how MATLAB uses the comments atthe beginning of an M-File and how to use foo to compute squareroots.

few lines (after the function declaration) are reserved for the function summary.This is the space to provide a short description of what the function does.

If the second line of code is a comment, it will show up in the “CurrentDirectory” window. Thus, one should provide a brief statement of the function’spurpose. It is very useful when trying to keep different functions organized.After saving the file, the reader can use the horizontal scroll bar to see theone-line function summaries. If the summaries do not appear in the CurrentDirectory window, try to refresh the display. To do this, right-click in theCurrent Directory window and select “Refresh”.

Every comment from the function declaration until the first line of the codeis considered part of the function description. To see this description, typehelp foo. In general, one can type:

help someFunction

and MATLAB will give a brief description of what the function does. Figure 4.2shows the MATLAB output when “help foo” is typed. It also shows how usefoo to compute square roots.

Page 33: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

30 Lesson 4: M-Files

4.4 Commenting

The importance of commenting cannot be stressed enough; it is vital to programmaintenance. When first writing any program, it is always easy to rememberwhat each line of code does. For instance, the computational code in Figure 4.1clearly shows that the program computes the square root of a number. However,it is much easier just to read the function description.

Place comments wherever necessary; give them their own lines or place themat the end of a command. It is advisable to have comments explaining a func-tion’s every section. It is also advisable to place comments for chunk of codethat may be difficult to understand by itself.

4.5 Multiple Return Values

Suppose a function has multiple outputs. For example, suppose

function [output1, output2] = functionName()

was the function declaration of an M-File. This particular function has twooutput variables. To receive both of them, it is necessary to specify two storagelocations when calling the program. If only one storage location is given, thenMATLAB will only store the first output variable.

These concepts are explained through the example shown in Figure 4.3. Theexample uses a function called max. When given a matrix, max returns a rowvector whose elements represent the maximum values of each column and a rowvector whose elements represent the row in which each maximum value wasfound. If max is passed an array (a row vector), then MATLAB will return two1 × 1 matrices. The first matrix represents the maximum value of the array,and the second matrix represents the index (in this case, column) in which themaximum value was found.

4.6 Exploration

The relative humidity and outside temperature combine in special ways to createa perceived temperature called the heat index. Write a function that accepts,as input arrays, the humidity and actual temperature measured each hour. Thefunction should have the following outputs:

1. An array containing the heat index at each time interval.

2. The maximum heat index (Use max).

3. The minimum heat index (Use min).

Page 34: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 4: M-Files 31

>> x = 1:10

x =

1 2 3 4 5 6 7 8 9 10

>> y = x .* (10-x)

y =

9 16 21 24 25 24 21 16 9 0

>> [maximumValue, maximumIndex] = max(y)

maximumValue =

25

maximumIndex =

5

>> maximumValue = max(y)

maximumValue =

25

Figure 4.3: Sample code demonstrating how MATLAB handles calls to func-tions that have multiple return variables. When passed an array,the function max returns both the maximum value of the array andthe index of the maximum value. To receive both variables, theuser must specify an array as the storage location. If the storagelocation is a single variable, then MATLAB will only return themaximum value in the array.

Page 35: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

32 Lesson 4: M-Files

In addition to three outputs, the function should also plot the heat indexalong with the actual temperature on a figure entitled “Temperatures”.

In the search for a heat index formula, the reader might find a general formulathat works only for certain humidity and temperature ranges. To make theformula more accurate, an additional formula might be included. In Section 5,the reader will learn how to handle these specific cases. As for now, just ignorethem and use the general formula in this exploration exercise.

Page 36: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 5

Flow Control

In this lesson, the reader will learn about relational operators, logical operators,while-loops, for-loops, if, elseif, and lastly, the else command. The reader shouldhave finished reading every preceeding lesson before continuing on.

5.1 Relational Operators

A relational operator is used to compare two elements. For example, considerthe conditional statement: 3 < 5. In this example, the relational operator wasthe “less than” sign. Had the example been 3 == 5, then the relational operatorwould have been the “equals” sign.

It is true that 3 is less than 5; thus, 3 < 5 is a true statement. It is false that5 is less than 3; thus, 5 < 3 would be a false statement. The ability to determinethe truth or falsity of conditional statements is a powerful programming toolthat MATLAB provides.

Figure 5.1 shows that MATLAB returns a 1 for true statements and a 0 forfalse statements. In total, there are six relational operators, and these are listedin Table 5.1.

Ideally, one would like to use relational operators alongside arrays. Whencomparing arrays, MATLAB does the comparisons element by element. Sup-pose, X and Y were arrays of equal length. The command X<Y would compareeach element of X with its corresponding element in Y . That is, X(1) wouldbe compared with Y(1). Now, if X were an array of different length, thenMATLAB will return an error stating that the matrix dimensions needed to beequal. However, if X were a scalar, then MATLAB would expand the size of Xto equal Y . Then, the comparison would occur. See Figure 5.2 for an example.

33

Page 37: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

34 Lesson 5: Flow Control

>> 3 < 5, 5 < 3

ans =

1

ans =

0

Figure 5.1: Sample code demonstrating that MATLAB returns a 1 when giventrue statements and a 0 when given false statements.

Relational Operator FunctionA < B Tests whether A is less than B.A > B Tests whether A is greater than B.A <= B Tests whether A is less than or equal to B.A >= B Tests whether A is greater than or equal to B.A == B Tests whether A is equal to B.A ∼= B Tests whether A is not equal to B.

Table 5.1: The six relational operators provided by MATLAB.Let A and B be statements.

>> X = 5; Y = 1:10;

>> X < Y

ans =

0 0 0 0 0 1 1 1 1 1

Figure 5.2: X was a scalar, so MATLAB expanded X to the same length asY . The expansion was done in such a way that every element ofthe expanded array had the same value as the scalar. The outputshows that 5 was not less than 1, 2, 3, 4, or 5 (these are representedby the zeros), but that 5 was less than 6, 7, 8, 9, and 10.

Page 38: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 5: Flow Control 35

>> i = 0; total = 0;

>> while i < 10

total = total + 2;

i = i + 1;

end

>> total

total =

20

Figure 5.3: Sample code demonstrating a while-loop.

5.2 Logical Operators

To create compound conditional statements, MATLAB provides three logicaloperators. These are: AND, OR, and NOT. The theory of formal logic willnot be discussed here, but the commands will prove useful to those readers whounderstand how to use them.

The AND symbol is given by &. The OR symbol is given by |, and the NOTsymbol is given by ∼. Any value not equal to zero is considered true. As anexample, -3 & 0 = 0 while -3 | 0 = 1.

5.3 While-Loops

The while-loop executes statements as long as its specified expression remainstrue. As an example, consider Figure 5.3.

To begin, i is set to zero, and total is also set to zero. This initializes thevariables. Then, the while-loop begins. It tests whether i is less than 10. Sincei=0, it is certainly true that i<10. Thus, the while-loop will begin to executeits statements. First, it takes the current value of total and adds two it. Thisresult is stored again as total. Second, the while-loop adds one to the currentvalue of i. The end marks the end of the while-loop statements. Since the loophas completed one cycle, it will now return to the conditional statement andbegin again.

This time around, i=1. However, it is still true that i<10, so the while-loopwill continue to execute its statements. This process will repeat until i=10.At this point, the while-loop will test to see if 10<10. Well, 10<10 is a falsestatement. This causes the while-loop to end. To see the final value of total,just type total, and MATLAB will return the value.

The advantage of the while-loop is that the user does not need to specifyexactly how many times the loop should repeat. This differs greatly from the

Page 39: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

36 Lesson 5: Flow Control

>> total = 0;

>> for i = 1:10

total = total + 2;

end

>> total

total =

20

>>

Figure 5.4: Sample code demonstrating a for-loop.

for-loop which is discussed in Section 5.4.

5.4 For-Loops

For-loops operate in a way similar to while-loops. The primary difference is thatfor-loops require the user to specify exactly how many times the loop shouldexecute. Now if this number is known, then a for-loop provides a much simplerway to repeatedly evaluate expressions. As an example, consider the sameexample from Section 5.3. See the code in Figure 5.4.

To begin, total is set to zero. Just like before, this initializes the variable.Then, the for-loop begins. This time, the command i = 1:10 specifies thati should be with the value of 1. Thus, the for-loop assigns i the value of 1and then proceeds to add 2 to the current value of total. Once the statementsare executed, the command end signals the for-loop would have automaticallyincremented the value of i by 1.

The increment value was specified with the command i = 1:10. Had thefor-loop been given the command i = 1:0.5:10, then the for-loop would auto-matically incremented the value of i by 0.5.

So now the current value of i is at 2. The for-loop will continue to add 2 tothe current value of total until i = 11. At that point, i is no longer less than10. Thus, the for-loop will have completed 10 cycles. Displaying the value oftotal reveals that the final total was 20.

5.5 If, Elseif, and Else

The if, else, and elseif commands are also similar to the loop commands inthat they all are related to conditional statements. However, these commands

Page 40: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 5: Flow Control 37

function [ classification ] = classify( input )

%CLASSIFY Determines whether the input is <,>, or == to 10.

if input < 10

classification = ’Input is less than 10.’;

elseif input > 10

classification = ’Input is greater than 10.’;

elseif input == 10

classification = ’Input is equal to 10.’;

else

classification = ’The input is not a number.’;

end

Figure 5.5: Sample code to implement the if, elseif, and else commands. Makesure this M-File is saved as “classify.m”.

only check to see if a condition is true; if it is, then they execute the commands intheir blocks. The elseif command provides an additional condition to check.The else command provides alternative statements to execute whenever theif-condition is not true. Lastly, the entire if block is ended using the end

command. As an example, consider the M-File in Figure 5.5.

Figure 5.6 shows how to generate the various function outputs. When thefunction begins, it tests whether the input is less than 10. If it is, then thefunction sets the classification to “Input is less than 10.”

If the input is not less than 10, then the function proceeds to check whetherthe input is greater than 10. If it is, then the function sets the classification to“Input is greater than 10.”

If the input is not greater than 10, then the function proceeds to checkwhether the input is equal to 10. If it is, then the function sets the classificationto “Input is equal to 10.”

Now, if the classify function determines that the input is not less than,greater than, or equal to 10, then the function sets the classification to “Inputis not a number.” This is done using the else command. The command end

then terminates the if-block.

5.6 Iterative Problem Solving

In Section 3.10, some calculus was required to determine the ball’s equations ofmotion. In this section, an alternative procedure will be used to determine theball’s equations of motion.

For a ball moving at constant velocity (v), the distance traveled (x) over atime interval (t), it determined by the formula: x = vt. This is the familiar

Page 41: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

38 Lesson 5: Flow Control

>> classify(9), classify(10), classify(11), classify(1:10)

ans =

Input is less than 10.

ans =

Input is equal to 10.

ans =

Input is greater than 10.

ans =

The input is not a number.

Figure 5.6: Sample code demonstrating how to generate the various outputsof the classify function.

Page 42: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 5: Flow Control 39

saying, “Distance equals rate times time.” Now, over a short time period, itwould be safe to say that the ball’s velocity was approximately constant. Thus,one could estimate the ball’s next position by adding to the current position,the product of its current velocity and a time interval. Stated mathematically:

xi+1 = xi + vx,i∆t

yi+1 = yi + vy,i∆t

The first equation says that the next horizontal position is equal to thecurrent horizontal position plus the horizontal distance traveled over a shorttime interval, ∆t. The second equation says that the next vertical position isequal to the current vertical position plus the vertical distance traveled over ashort time interval, ∆t. As ∆t gets smaller and smaller, one would expect theapproximation to get better and better.

It is also possible to estimate the next velocity of the ball based on informa-tion about the current velocity of the ball. As for horizontal velocity, one wouldexpect it to remain constant (as long as air resistance is neglected). For thevertical component of velocity, however, velocity does change. In fact, gravitypulls it down at 9.8 m/s2. Using a similar style, the next velocities can be statedmathematically as well:

vx,i+1 = vx,i

vy,i+1 = vy,i − 9.8∆t

The first equation says that the next horizontal velocity is equal currenthorizontal velocity. The second equation says that the next vertical velocityis equal to the current vertical velocity minus the effect gravity has over thevelocity on a short time interval ∆t.

As long as the initial positions and velocities are known, according to theseequations, it should be possible to determine the position and velocity of theball at any time in the future! To keep track of the position and velocity atmany points, it would make sense that the user should use a for-loop. Figure 5.7shows how to do this.

The code first sets ∆t = 0.1, the initial positions to 0, and the initial veloc-ities to 10. Then, it enters the for-loop and computes the next positions basedon the current positions and current velocities. Then it computes the next ve-locities. This process repeats a total of 5 times. Each time, the for-loop storesthe positions and velocities in the arrays x, y, dx, dy.

Page 43: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

40 Lesson 5: Flow Control

>> dt = .1; x(1) = 0; y(1) = 0; dx(1) = 10; dy(1) = 10;

>> for t=1:5

x(t+1) = x(t) + dx(t) * dt;

y(t+1) = y(t) + dy(t) * dt;

dx(t+1) = dx(t);

dy(t+1) = dy(t) - 9.8 * dt;

end

>> x, dx, y, dy

x =

0 1 2 3 4 5

dx =

10 10 10 10 10 10

y =

0 1.0000 1.9020 2.7060 3.4120 4.0200

dy =

10.0000 9.0200 8.0400 7.0600 6.0800 5.1000

Figure 5.7: Sample code to demonstrate how to store the ball’s positions andvelocities.

Page 44: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 5: Flow Control 41

A == B Equivalence. 1 if A is equal to B, else 0.A > B 1 if A is greater than B, else 0.A < B 1 if A is less than B, else 0.A >= B 1 if A is greater than or equal to B, else 0.A <= B 1 if A is less than or equal to B, else 0.A = B 1 if A is not equal to B, else 0.A & B AND. 1 if both A and B are non-zero, else 0.A | B OR. 1 if A, B, or A and B are non-zero, else 0.∼A NOT. 1 if A is 0, else 0.while (condition) Repeats a block while condition is true.if (condition) Executes a block once, if condition is true.elseif (condition) An alternative block to execute

while within an if statement.else An unconditioned alternative block to execute

while within an if statement.for X = RANGE Repeats a block, setting X each

time to elements in RANGE.end Ends a block of commands.

Table 5.2: A summary of the commands covered in Lesson 5.

5.7 Summary

This lesson has introduced the basics of flow control and iterative problem solv-ing. To create powerful M-Files, it is necessary to understand the concepts andcommands introduced here, and it is strongly suggested that the reader taketime to learn them all. Explore the help files and discover some other tools touse. Table 5.2 summarizes some of the commands covered in this lesson.

5.8 Exploration

Create a function that determines the throwing angle needed to maximize thehorizontal distance traveled. Your file should accept the initial vertical positionand initial throwing velocity as inputs, and it should output the optimum angle.

Page 45: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make
Page 46: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 6

Advanced Plotting

The reader should complete Lessons 2 and 3 before beginning this lesson. Thislesson will cover addition plotting functions that might be of use in later MAT-LAB projects. It will also prepare the way for animations.

6.1 Surface Plots

Thus far, only lines have been plotted. Now, the reader will learn to plot datasurfaces using the two methods. A data surface is a set of data whose pointsvary across two axes rather than one. As an example, consider a map of variousmountain heights. To locate any mountain, it is necessary to specify both alongitude and latitude coordinate. That is, two axes determine the location ofa mountain, and from that location, the height can then be specified.

Now, consider a 2 × 2 matrix such as the one shown in (6.1).

A =

[a1,1 a1,2

a2,1 a2,2

]

(6.1)

The reader should know that each element is determined by two coordinates(a row and a column). For example, a1,1 is in the first row and first column,and a1,2 is in the first row and second column. The rows and columns can alsobe thought of as y- and x-coordinates. Since the columns progress horizontally,it would make sense to refer to the columns as the x-coordinate. Since the rowsprogress vertically, they can be thought of as the y-coordinates. Thus, eachelement in a matrix can be referenced by ay,x where y represents the row of theelement and x represents the column of the element.

If the matrix A is given real values, then the command surf(A) can be usedto plot each element within the matrix. Each element is placed according to itscoordinates. Thus, ay,x is placed at the coordinate (x, y). The z-coordinate at

43

Page 47: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

44 Lesson 6: Advanced Plotting

(x, y) is determined by ay,x. As an example, suppose a2,1 = 5. Then MATLABwould plot the point (1, 2, 5).

Figure 6.1 shows how MATLAB plots the elements of a matrix. It is im-portant to note that MATLAB essentially flips the the matrix vertically whenplotting. This happens because matrices use a left-handed coordinate systemto reference their elements. However, a right-handed coordinate system is usedby MATLAB when plotting.

Now, there really is a better way to create surfaces. Instead of using anelement’s coordinates to determine where it should be plotted, it would makemuch more sense to actually specify those coordinates. Thus, the independentvariable (which is a matrix) will require two matrices as inputs. Those inputswill give the coordinates for each element in the output matrix.

Consider the three-dimensional function: z = xy. To plot this function, thereader should first create two matrices that represent the coordinates of thexy-plane. This will be done from −10 to 10, and it can be seen in the first fourlines of Figure 6.2. The reader may choose to view the variables and verify whatthe commands created.

Now, to plot the function, it is necessary to create a third matrix Z. Sincez = xy, the reader should make Z = X .* Y. Thus, every element in Z will bethe product of an x- and y- coordinate. Now, the surface can be plotted withsurf(X,Y,Z). This command works like plot or plot3, but it creates a coloredsurface plot of the data found in Z. The coordinate of each data point will bedetermined by its corresponding elements in the X and Y matrices. The completecode required to create this plot can be found in Figure 6.2. The plot can befound in Figure 6.3.

6.2 Color Maps and Pcolor

When plotting surfaces, MATLAB using a color map to determine the plot’svarious colors. The color editor can be used to create new color maps or toselect from a list of standard color maps. However, built-in color maps can beselected at the command line. Recreate the figure from the last section andthen type the commands found in Figure 6.4. After typing each command, lookback at the figure and see how it has changed. Experiment with the color mapeditor. For further information, seek the MATLAB help files.

The pcolor function is similar to the surface function (it accepts the samearguments). The major difference is that it does not plot a 3D image. Instead,it uses a color map to produce a 2D colored image. In Section 6.3, an examplewill demonstrate how to use the pcolor command.

Page 48: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesso

n6:A

dvanced

Plo

tting

45

y, row

x, column

a1,1 a1,2

a2,1 a2,2

x

y

z

(0, 0) (1, 0) (2, 0) (3, 0) (4, 0)

(0, 1)

(0, 2)

(0, 3)

(0, 4)

Matrix 3D Plot

Figure 6.1: When plotting a matrix, MATLAB plots the element ay,x at the coordinate (x, y). Notice that the matrix isessentially flipped vertically when plotting its coordinates. Remember this fact when making comparisons betweenthe graph and matrix.

Page 49: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

46 Lesson 6: Advanced Plotting

>> scale_x = -10:10;

>> X = ones(size(scale_x))’ * scale_x;

>> scale_y = -10:10;

>> Y = scale_y’ * ones(size(scale_y));

>> Z = X .* Y;

>> surf(X,Y,Z);

Figure 6.2: Sample code demonstrating how to plot the function z = xy.

−10

−5

0

5

10

−10

−5

0

5

10−100

−50

0

50

100

Figure 6.3: The surface generated by the code in Figure 6.2.

>> colormap(hot(6))

>> colormap(hot(8))

>> colormap(hot(100))

>> colormap(bone(16))

>> colormap(vga)

>> colormap(hsv(128))

>> colormap(cool(8))

>> colormapeditor

Figure 6.4: Sample code demonstrating how to select different color maps.

Page 50: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 6: Advanced Plotting 47

>> x = -10:10;

>> subplot(3, 1, 1);

>> plot(x, x);

>> subplot(3, 1, 3);

>> plot(x, x .^ 3 - 25 * x);

>> subplot(3, 1, 2);

>> plot(x, sqrt(abs(x)));

Figure 6.5: Sample code demonstrating how to create Figure 6.6.

6.3 Subplot

The subplot command allows the user to place multiple plots within the samefigure. When used, it divides the active figure into sections; then, it activatesone of those sections (a user-specified section). When using subplot, the firstvariable represents the number of rows the figure should have. The secondnumber determines how many columns the figure should have. The third numberrepresents the section that should be activated. The sections can be referencedby numbers that begin counting at 1 from the upper left-hand section andincrease from left to right, top to bottom.

As an example, suppose that subplot(2,2,3) was input into the commandline. This divides the figure into a 2×2 matrix. That is, there will be 4 subplots(2 subplots per row for 2 rows). In this example, 3 tells MATLAB to activatethe plot in the second row and first column.

As another example, consider Figure 6.5. This code will create space forthree graphs. It helps to think of it as a 3×1 matrix. Then, the code will displaya plot in each section. Notice that the grid dimensions were specified each timesubplot was called. Further, subplot was called each time the user needed toactivate a different subplot. The resulting figure can be seen in Figure 6.6.

As promised, an example usage of the pcolor function can be found inFigure 6.7. The result can be seen in Figure 6.8.

6.4 References

Every time a plot, figure, or any other object is produced, MATLAB associates areference to that object. MATLAB also provides the ability to store an object’sreference. The reader may have noticed MATLAB’s references in an earlier les-son (specifically relating to the figure command). To store an object reference,the reader should make an assignment to the command that created the object.For example, imaref = plot(1:10) assigns the reference of the created plot tothe variable imaref.

Page 51: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

48 Lesson 6: Advanced Plotting

−10 −8 −6 −4 −2 0 2 4 6 8 10−10

−5

0

5

10

−10 −8 −6 −4 −2 0 2 4 6 8 10−1000

−500

0

500

1000

−10 −8 −6 −4 −2 0 2 4 6 8 100

1

2

3

4

Figure 6.6: The figure generated by the code in Figure 6.5.

>> x = -10:10;

>> X = ones(size(x))’ * x;

>> y = -10:10;

>> Y = y’ * ones(size(y));

>> Z = X .* Y;

>> figure;

>> subplot(2,1,1); pcolor(X);

>> subplot(2,1,2); pcolor(X,Y,Z);

Figure 6.7: Sample code demonstating how to use the pcolor function. Theresult can be seen in Figure 6.8.

Page 52: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 6: Advanced Plotting 49

2 4 6 8 10 12 14 16 18 20

5

10

15

20

−10 −8 −6 −4 −2 0 2 4 6 8 10−10

−5

0

5

10

Figure 6.8: The graphic generated by the code in Figure 6.7.

Once a plot reference has been set, it is then possible to modify the propertiesof that object. For instance, to modify the “Line Style” property, the readerwould use the set command. The first argument should be the object reference.The second argument should be the string ’LineStyle’, and the third argumentshould be one of those found in Table 6.1. Figure 6.9 shows how to use thesecommands. Some other property values can be found in Table 6.2.

>> x = 1:10;

>> plotReference = plot(x, x .^ 3 - x * 30);

>> set(plotReference, ’LineStyle’, ’:’);

>> set(plotReference, ’Marker’, ’+’);

>> set(plotReference, ’Color’, [1 0 0]);

Figure 6.9: Sample code demonstrating how to use the set command. Theplot can be found in Figure 6.10.

Page 53: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

50 Lesson 6: Advanced Plotting

Line Style Description Marker Description

’-’ for a solid line ’+’ for + markers’--’ for a dashed line ’o’ for o markers’:’ for a dotted line ’*’ for * markers’-.’ for a dash-dotted line ’x’ for x markers’none’ for no line ’s’ for square markers

’s’ for square markers’d’ for diamond markers

’none’ for no markers

Table 6.1: Argument options for the set command.

Property Value

MarkerSize a number to specify marker sizeLineWidth a number to specify line widthMarkerColor an RGB array (such as [0 .5 1]) to specify marker color

Color an RGB array (such as [0 .5 1]) to specify line colorXData an array that will update the plot’s x-coordinatesYData an array that will update the plot’s y-coordinatesZData an array that will update the plot’s z-coordinatesCData an array that will update the plot’s pcolor values

Table 6.2: Here are some other set properties.

Page 54: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 6: Advanced Plotting 51

1 2 3 4 5 6 7 8 9 10−100

0

100

200

300

400

500

600

700

Figure 6.10: The plot generated by the code in Figure 6.9.

6.5 Title Function

To set the title of a plot, pass a string to the title command. An examplewould be: title(’Hello’). Notice that this command titles a plot (which isdifferent from the figure title). Thus, subplots can have different titles. Otherfeatures can also be edited from the figure menus (Tools → Edit Plot). Theseoften provide quick easy customizations such as labeling the x- and y- axes. Formore information about customizations, see the MATLAB help files.

6.6 Text

It is also possible to add text objects to plots. As an example, suppose onewanted to display the minimum point on a graph. To do this, call the text

command. In a 2D plot, one only needs to pass the text command an x- andy- coordinate. If the plot is 3D, then the z-coordinate will also need to bepassed. The final variable to pass is the string to be displayed. The readershould notice that a text object has XData and YData properties. Thus, thetext can be moved with the set command as long as the reference was savedduring creation. Figure 6.11 shows how to display text on a plot.

Page 55: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

52 Lesson 6: Advanced Plotting

>> x = -100:100;

>> y = 5 - 20 * x + 3 * x .^ 2;

>> plot(x,y);

>> [c,i] = min(y);

>> text(x(i),y(i),’<------ this is the minimum’);

Figure 6.11: Sample code showing how to display text on a plot. The resultcan be found in Figure 6.12.

−100 −80 −60 −40 −20 0 20 40 60 80 100−0.5

0

0.5

1

1.5

2

2.5

3

3.5x 10

4

<−−−−−− this is the minimum

Figure 6.12: The plot generated by the code in Figure 6.11.

Page 56: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 6: Advanced Plotting 53

surf(A) A surface of the elements of A.surf(A,B,C) A surface of C’s elements at

the locations specified by A and B.pcolor(A) A 2D color plot of A’s elements.pcolor(A,B,C) A 2D color plot of C’s elements at

the locations specified by A and B.colormap(map) Sets the color map to map.set(ref,’property’,value) Sets property to value for

the object referenced by ref.See Tables 6.1 and 6.2 for details.

title(’theTitle’) Sets the plot title to theTitle.text(x,y,’text’) Places text at (x, y).text(x,y,z,’text’) Places text at (x, y, z).

Figure 6.13: A summary of the commands learned in Lesson 6.

6.7 Summary

In this lesson, the reader learned some of MATLAB’s advanced plotting features.There are many more, and it is suggested that the reader check the MATLABhelp files for more information. Table 6.13 is a summary of the commandslearned in this lesson. Let A, B, and C be matrices. Let map be a colormap.

6.8 Exploration

Plot a green, spiral sphere and a red, spiral cube on the same plot.

Page 57: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make
Page 58: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 7

Animations

The reader should complete Lessons 5 and 6 before beginning this lesson. Thislesson will teach the reader how to create animations with MATLAB.

7.1 Opening a Movie File for Output

First of all, please note that the words “movie” and “animation” will be usedinterchangablly. Now, in order to make a movie, there must be an active plot.Also, it is important that one does not switch plots, resize the figure window, orput any other window over the figure window. MATLAB essentially capturesthe area of the figure window. If another window is placed over the figurewindow, it also will be captured and included into the movie. To get started,create a plot using the commands in Figure 7.1. Note that the last line createsa new movie file. Do not close the figure window.

Additionally, the last command in Figure 7.1 will write over any previousfile named “test.avi”. The reader should notice that the avifile commandreturns the info about the movie file created (unless the output is suppressed).Lastly, it should be mentioned that avifile will assume default values for itsadjustable parameters, if they are not specified.

It is important to note that MATLAB retains a lock on any file you open.The lock has the effect that no other programs can modify the file while it is

>> x = 0:0.1:10;

>> y = x.^2;

>> p = plot(x,y);

>> movie = avifile(’test.avi’)

Figure 7.1: Sample code demonstrating how to create a movie.

55

Page 59: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

56 Lesson 7: Animations

open (not even the Windows operating system). By assigning the handle fromavifile to the variable movie, the reader has retained the ability to close thefile later on. This is important, otherwise the movie might not be viewable(since it would still be locked).

When an plot’s reference is stored, MATLAB returns a number. However,when handling animation objects, it is the actual object gets stored in thevariable. For example, look in the “Workspace” window. There will be a variableentitled “movie”; MATLAB will show that it is a 1× 1 object. However, it willtake up thousands of bytes of space.

7.2 Adding Frames to the Movie

Movie files contain many images projected one after another. Each image differsslightly from the previous image in such a way that when viewed consecutively,it looks like one picture with objects moving within it.

Each of these images is called a frame. To get a frame from the plot, usethe getframe command. It is possible to assign the frame’s return value to avariable. Then the frame could be added to the animation with the addframe

command. See Figure 7.2.

Warnings may or may not appear, but they are normal. Movie files some-times have special requirements that must be met to function properly; thusMATLAB changes the size of the plot slightly to fit those requirements. Nowthat a frame has been added, the movie has one frame.

To add a few more frames, change the power of x slightly. Then re-plot(using the set command), and add the frame. It is possible to add the framedirectly by placing getframe into the addframe command. See Figure 7.3.

7.3 Closing the Movie File

The last step is the simplest one. To close the movie file, use the close com-mand. Pass it the variable referencing the movie, and save the return value asthe same variable. This is done so that MATLAB can clear the old value ofthe OPEN file. By saving the return value, the variable will now reference aCLOSED file. This cleans up all loose ends and allows the file to be viewed.See Figure 7.4.

Now, look into the “Current Directory” window, and there should be a filenamed “test.avi”. Double-clicking the file will bring up an ”Import Wizard”window. For right now, just click on ”Play Movie”. Then an animation willappear showing an animated graph.

Page 60: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 7: Animations 57

>> frame1 = getframe

frame1 =

cdata: [343x435x3 uint8]

colormap: []

>> movie = addframe(movie, frame1)

Warning: The frame height has been padded to be a multiple

of four as required by Intel Indeo.

> In C:\MATLAB6p5\toolbox\matlab\iofun\@avifile\addframe.m

at line 139

Warning: The frame width has been padded to be a multiple

of four as required by Intel |Indeo.

> In C:\MATLAB6p5\toolbox\matlab\iofun\@avifile\addframe.m

at line 145

Adjustable parameters:

Fps: 15.0000

Compression: ’Indeo3’

Quality: 75

KeyFramePerSec: 2.1429

VideoName: ’test.avi’

Automatically updated parameters:

Filename: ’test.avi’

TotalFrames: 1

Width: 436

Height: 344

Length: 0

ImageType: ’Truecolor’

CurrentState: ’Open’

Figure 7.2: Sample code demonstrating how to add a frame to the currentmovie.

Page 61: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

58 Lesson 7: Animations

>> y = x.^1.5; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^1.0; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^0.5; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^0.2; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^0.1; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^0.050; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^0.025; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^0.010; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^0.005; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

>> y = x.^0.000001; set(p, ’YData’, y);

>> movie = addframe( movie, getframe);

Figure 7.3: Sample code demonstrating how to had multiple frames.

>> movie = close(movie)

Adjustable parameters:

Fps: 15.0000

Compression: ’Indeo3’

Quality: 75

KeyFramePerSec: 2.1429

VideoName: ’test.avi’

Automatically updated parameters:

Filename: ’test.avi’

TotalFrames: 11

Width: 436

Height: 344

Length: 0

ImageType: ’Truecolor’

CurrentState: ’Closed’

Figure 7.4: Sample code demonstrating how to close a movie file.

Page 62: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 7: Animations 59

7.4 M-Files that Produce Animation Files

In M-Files, it is important to use try-catch statements; this makes sure that thefile does not remain locked. If an animation file is created within an M-File,it is saved as a local variable. However, once the M-File finishes evaluating itscode, all the local variables will be destroyed (and the movie will be transferedto a permanent file.

It is true that one could just place the close command at the end of anM-File, but what would happen if an error occurred during the execution of theM-File? Well, MATLAB would quit executing the M-Files’s commands, andthen, the movie file would remain locked (since it would have not been closed).

To avoid this, make sure to place all commands between the opening andclosing of an animation into a try-catch statement. Refer to Figure 7.5. Aftersetting up the data for the plot, an animation file is opened by the name of“test.avi”. All successive movie commands appear inside the try statement.

7.5 Exploration

In the exploration for Lesson 5, multiple projectile motion trajectories were plot-ted. In each plot, the throwing angle was changed in order to find the optimumangle that maximized the distance traveled. Now, do something very similar.This time, instead of plotting multiple plots simultaneously, plot each angle asa separate frame in an animation. Make sure to use the axis() command sothat the axes will stay the same throughout.

7.6 Summary

In this section, the basics of animations were introduced. Table 7.6 summarizesthe commands introduced in this lesson. Refer to the MATLAB help files formore detailed information.

Page 63: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

60 Lesson 7: Animations

% set up data. Change this for your plot

x = 0:0.02:1;

y = x .^ 0.0;

p = plot( x, y, ’LineWidth’, 3);

axis([0 1 0 1])

%

% Start animation

%

% open animation file with quality set to 95 percent

avi = avifile(’test.avi’,’Quality’,95);

try

avi = addframe(avi, getframe);

%

% This is animation code in this block of indented code

%

for framenumber = 1:100

% update plot here based on frame number

% this is an example with different powers for X

y = x .^ (framenumber / 50);

set( p, ’YData’, y );

avi = addframe(avi, getframe);

end

catch

% uh oh, if we end up here, that means

% an error occured durring animation

avi = close(avi);

% after closing the animation, throw the

% error again to show user what error occured

error(lasterr)

end %%% end try-catch block

% if here, no error occured. close normally

avi = close(avi)

Figure 7.5: Sample code for an M-File that produces an animation.

Page 64: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 7: Animations 61

try catch end Commands for catching errors.a = avifile(FILENAME) Creates a movie entitled FILENAME

and stores the reference as af = getframe Stores the current plot in frame f.a = addframe(a,f) Adds frame f to the movie referenced by a.a = close(a) Closes the movie referenced by a.error() Throws an error.lasterr A variable holding the last error that occurred.

Figure 7.6: A summary of the commands introduced in Lesson 7.

Page 65: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make
Page 66: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Lesson 8

The End

Well, the book is over now. There is still much to learn about MATLAB.The help files included with MATLAB are the best resource available. In theappendix, the reader will find solutions to the exploration sections that appearedin each chapter.

63

Page 67: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make
Page 68: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Appendix A

Exploration Answers

This section provides the solutions to the exploration sections that appeared inthe earlier lessons.

A.1 Introduction

The key to this problem is a coordinate shift. Align the axes so that the slopeof the x-axis equals the slope of the wedge. Next, find the magnitude of thecomponent of the gravitational force (Fg,y) in the direction of the new y-axis.Notice that the magnitude of the gravitational force due to gravity is Fg = mg.Since the block is at rest, the magnitude of the normal force (FN ) must equalthe magnitude of component of the gravitational force (Fg,y). Of course, unitsare always important (the answer should be in Newtons).

>> degrees2radians = 2 * pi / 180;

>> angleDegrees = 20;

>> angleRadians = angleDegrees * degrees2radians;

>> mass = 200;

>> gavity = 9.8;

>> magGForce = mass * gravity;

>> componentGForce = magGForce * cos(angleRadians);

>> normalForce = componentGForce

normalForce =

1.5014e+003

Figure A.1: Source code for Section A.1. Thus, the magnitude of the normalforce is approximately 1.5 kN.

65

Page 69: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

66 Appendix A: Exploration Answers

A.2 Matrices

To verify the properties of Section 2.8, it will suffice find an example that works.Remember, not every matrix is invertible. Thus, invertible matrices must beused to verify some of these properties. However, it should be mentioned thatsome of these properties hold for all matrices. To satisfy all the properties withtwo matrices, pick any two invertible matrices. Then, evaluate the left-handside of the property. Then evaluate the right-hand side of the property. Verifythat the evaluations are equal.

If the reader is having difficulty finding two invertible matrices, try these:

A = [1 2; 3 4], B = [4 -2; -3 1]

A.3 Arrays and Basic Plotting

The position formulas are given by:

x = (5 cos θ)t

y = (5 sin θ)t − 5t2

The code required to determine the output can be found in Figure A.2.

A.4 M-Files

Figure A.3 shows the source code to compute the heat index. Since the programhas two output variables, the user should specify two storage locations whencalling the program. This can be seen in Figure A.4. Remember, the functioncan be called only if it is located within the current directory.

A.5 Flow Control

Figure A.6 shows how to generate the answer from the M-File listed in Fig-ure A.5. The key to this problem was a for-loop. The for-loop should have triedall angles from 0◦ to 90◦ and picked the angle that sent the ball the furthest.

A.6 Advanced Plotting

There are many ways to draw a green, spiral circle and red, spiral cube. Thecode in Figure A.7 is just one way of doing so. Examine the code and try anddetermine “why” it works. The resulting graphic is in Figure A.8.

Page 70: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Appendix A: Exploration Answers 67

>> t = 0:.1:2;

>> angleRadians = 0 * pi / 180;

>> x = 5 * cos(angleRadians) * t;

>> y = 5 * sin(angleRadians) * t - 5 * t .^ 2;

>> figure(’name’,’Projectile Motion’);

>> plot(x,y);

>> hold on;

>> angleRadians = 15 * pi / 180;

>> x = 5 * cos(angleRadians) * t;

>> y = 5 * sin(angleRadians) * t - 5 * t .^ 2;

>> plot(x,y);

>> angleRadians = 30 * pi / 180;

>> x = 5 * cos(angleRadians) * t;

>> y = 5 * sin(angleRadians) * t - 5 * t .^ 2;

>> plot(x,y);

>> angleRadians = 45 * pi / 180;

>> x = 5 * cos(angleRadians) * t;

>> y = 5 * sin(angleRadians) * t - 5 * t .^ 2;

>> plot(x,y);

>> angleRadians = 60 * pi / 180;

>> x = 5 * cos(angleRadians) * t;

>> y = 5 * sin(angleRadians) * t - 5 * t .^ 2;

>> plot(x,y);

Figure A.2: Source code for Section A.3. The optimum angle for horizontaldistance is 45◦. There is no need to proceed past 60◦ since thehorizontal distance began to decrease after 45◦.

Page 71: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

68 Appendix A: Exploration Answers

function [HI, maxHI, minHI] = heatIndex(T, R)

%heatIndex computes the heat index

% HI stands for "heat index"

% R stands for "relative humidity"

% T stands for "temperature"

% It requires T and R.

% Obviously, these arrays must be the same size.

% It returns HI, minHI, and maxHI.

% It plots HI and T on the same graph.

% The HI formula determined by Lans P. Rothfusz in 1990.

% http://www.hpc.ncep.noaa.gov/heat_index/hi_equation.html

% Visited: 2003.04.20

% This version is not accurate when

% R < 13 and 80 <= T <= 112

% or when

% R > 85 and 80 <= T <= 87

HI = -42.379 + 2.04901523 * T + 10.14333127 * R;

HI = HI - .22475541 * T .* R - .00683783 * T .^ 2;

HI = HI - .05481717 * R .^ 2 + .00122874 * T .^ 2 .* R;

HI = HI + .00085282 * T .* R .^ 2 - .00000199 * T .^2 .* R .^ 2;

figure(’name’,’Temperatures’)

plot(HI)

hold on

plot(T)

maxHI = max(HI);

minHI = min(HI);

Figure A.3: Source code for Section A.4. Save this M-File as “heatIndex.m”.

Page 72: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Appendix A: Exploration Answers 69

>> [HI, maxHI, minHI] = heatIndex(120:-10:70, 30:10:80)

HI =

148.0129 135.6570 118.3158 99.6777 82.9534 70.8761

maxHI =

148.0129

minHI =

70.8761

Figure A.4: Sample code demonstrating how to receive the output from thefunction shown in Figure A.3.

Page 73: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

70 Appendix A: Exploration Answers

function [ bestAngle ] = ball(yinitial, speed)

%BALL Determines the optimum throwing angle

% Requires the initial throwing height

% Requires the initial throwing speed

% clear all matrices

x = 0; y = 0; dx = 0; dy = 0;

g = 9.8; % gravitational constant

% set initial bests

bestDistance = 0;

bestAngle = 0;

for theta=0:90

dt = .01; % change in t

x(1) = 0;

y(1) = yinitial;

dx(1) = speed * cos(theta * pi / 180);

dy(1) = speed * sin(theta * pi / 180);

% after 1000 sec, the ball should hit the ground

for t=1:1000

x(t+1) = x(t) + dx(t) * dt;

y(t+1) = y(t) + dy(t) * dt;

if y(t+1)<0 % if y<0, ball hit the ground

dx(t+1) = 0;

dy(t+1) = 0;

else % otherwise, keep checking

dx(t+1) = dx(t);

dy(t+1) = dy(t) - g * dt;

end

end

% set the new best, if needed

if x(1001) > bestDistance

bestDistance = x(1001);

bestAngle = theta;

end

end

Figure A.5: Source code to determine the best throwing angle. Make sure tosave the M-File as “ball.m”.

Page 74: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

Appendix A: Exploration Answers 71

>> ball(0,10)

ans =

45

>> ball(10,10)

ans =

29

>> ball(20,10)

ans =

25

Figure A.6: Sample code generating the best angle for various initial heightsand velocities from the function shown in Figure A.5

>> xSphere = -1:0.01:1;

>> ySphere = sin(xSphere*30) .* (1-xSphere.^2);

>> zSphere = cos(xSphere*30) .* (1-xSphere.^2);

>> plot3(xSphere,ySphere,zSphere, ’Color’, [0,1,0]);

>> xCube = -1:0.1:1;

>> yCube = sin(xCube * pi / .2 + (pi / 4));

>> zCube = cos(xCube * pi / .2 + (pi / 4));

>> hold on

>> plot3(xCube,yCube,zCube, ’Color’, [1,0,0]);

>> set(gca, ’Box’, ’on’)

Figure A.7: Sample code demonstrating how to draw a green, spiral circle anda red, spiral cube. The plot can be found in Figure A.8.

Page 75: Introduction to MATLAB - University of New Mexicowilliams/cs530/matlab4_folie.pp4.pdfMATLAB is a numerical package geared toward engineering applications, espe-cially those which make

72 Appendix A: Exploration Answers

−1

−0.5

0

0.5

1

−1

−0.5

0

0.5

1−1

−0.5

0

0.5

1

Figure A.8: The plot generated by the code in Figure A.7.