introduction to matlab programming -...

14
Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016) Appendix D Introduction to MATLAB Programming Contents D.1 Getting Started ............................. 2 D.2 Basic m-file ................................ 3 D.2.1 Printing .................................. 5 D.3 Basic Plotting .............................. 7 D.3.1 Legends .................................. 8 D.3.2 Saving and Printing Plots ........................ 9 D.4 If/Else/Break/Return .......................... 10 D.5 Function Programs ........................... 11 D.6 Entering Matrices and Vectors .................... 13 D.6.1 Row and Column Manipulation ..................... 14 June 18, 2016 The following is a brief introduction to using MATLAB. This is not intended to provide a listing of various MATLAB commands, but illustrate how simple MATLAB programs are formed. The goal is to get you started, and to also provide enough information that you can use the very good help facility that comes with MATLAB (most people who use MATLAB make frequent use of the help pages). It is also assumed that you have a basic, but perhaps imperfect, understanding of coding. This means that you are aware that there are such things as for-loops and if/then/else type statements, although unclear of their exact formatting. Finally, for many of the commands or actions that are considered, there are likely other ways to accomplish the same thing. Some of them possibly simpler, or maybe more clever, than what is shown here. Caveat: The examples are worked out using a Mac implementation of MATLAB. It’s assumed similar responses are obtained using other implementations. 1

Upload: truongkhanh

Post on 05-May-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

Appendix D

Introduction to MATLAB

Programming

Contents

D.1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

D.2 Basic m-file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

D.2.1 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

D.3 Basic Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

D.3.1 Legends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

D.3.2 Saving and Printing Plots . . . . . . . . . . . . . . . . . . . . . . . . 9

D.4 If/Else/Break/Return . . . . . . . . . . . . . . . . . . . . . . . . . . 10

D.5 Function Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

D.6 Entering Matrices and Vectors . . . . . . . . . . . . . . . . . . . . 13

D.6.1 Row and Column Manipulation . . . . . . . . . . . . . . . . . . . . . 14

June 18, 2016

The following is a brief introduction to using MATLAB. This is not intended to providea listing of various MATLAB commands, but illustrate how simple MATLAB programs areformed. The goal is to get you started, and to also provide enough information that you canuse the very good help facility that comes with MATLAB (most people who use MATLABmake frequent use of the help pages). It is also assumed that you have a basic, but perhapsimperfect, understanding of coding. This means that you are aware that there are such thingsas for-loops and if/then/else type statements, although unclear of their exact formatting.Finally, for many of the commands or actions that are considered, there are likely other waysto accomplish the same thing. Some of them possibly simpler, or maybe more clever, thanwhat is shown here.

Caveat: The examples are worked out using a Mac implementation of MATLAB. It’s assumedsimilar responses are obtained using other implementations.

1

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.1 Getting Started

The tool bar and window arrangement when you start MATLAB is shown in Figure D.1. Theworksheet area, what is called the Command Window, is seen and it contains the >> prompt.Commands can be typed directly into the worksheet, including comment lines. Of more in-terest here are when the commands are contained in an m-file, and the file run as a program.How this is done is explained shortly, but it is first necessary to consider where the m-filesare located. MATLAB will, by default, assume they are located in Documents/MATLAB. Ifyou prefer to locate them in one or more other folders you need to tell MATLAB where tolook. This can be done using the set path option. This needs to only be done once. So, afterstarting MATLAB, click on the folder icon (see Figure D.1). You will then be able to selectwhatever folder or folders you plan to use. The only time you will ever need to do this againis when you upgrade MATLAB or decide to include other folders.

Figure D.1: Folder icon, in red box, selected to set path for location of MATLAB files. Notethe question mark in the upper right corner; this provides access to the help pages.

When you open an m-file its contents are shown in the Editor window. As an example,in Figure D.2 the m-file ss.m has been opened (only the first line is shown). It is sharing thework area with the Command Window. The latter is now grayed out, and to bring it to thefront you just click on it. If you want to see both at the same time you can undock one ofthem. This is done using the inverted triangle as shown in Figure D.2.

Figure D.2: To undock the Editor window, use the inverted triangle in the red box.

2

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.2 Basic m-file

To begin, in Example 1 in Section 1.1 the sum

S(n) =nX

j=1

1

j

(D.1)

was considered. A MATLAB m-file named ss.m was created to compute this for n =10, 102, 103, and then print the results. The file is shown in Figure D.3. Note that theseare simple text files that are named so they have a .m ending. As such, they can be createdand then edited using a text editor (as illustrated in the top of Figure D.3), or created andedited using MATLAB (as illustrated in the bottom of Figure D.3). To create it in MATLAB,you first click on the New Script icon in the tool bar (see Figure D.1). This will open a blankwork area in the Editor, and you then simply type in the commands as they appear in FigureD.3. Once finished, you save it by either clicking on the Save icon (see Figure D.2), or usethe usual keystrokes for saving a file.

Figure D.3: The m-file ss.m used to compute S(n) in (D.1). Top: file when opened using atext editor. Bottom: file when opened using MATLAB.

3

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

A synopsis of the commands in ss.m are given below.

for-loop with index ic

comment line

for-loop used to compute series

print values of n and S

A couple of additional comments related to the commands used.

for-loops: The for-loop starting on line 3 uses the values 1, 2, 3 (in that order). If youwanted the values to increase by, say, 4 each time, then ic = 1:3 is replaced with ic =1:4:13. With this, the values for ic are 1, 5, 9, 13. Similarly, suppose you wanted touse, in order, 7, 5, 3, 1. In this case ic = 1:3 is replaced with ic = 7:�2:1. Note thatthere are also while-loops, which are very useful, and an example is given in Section D.5.

fprintf : This command contains the formatting to be used, with n written in integer formatand S in exponential format. By default, the output appears in the Command Window.To find out about the format options, consult the help page for fprintf.

To run the commands in ss.m, with the file open in MATLAB’s Editor as illustrated inthe bottom of Figure D.3, click on the green Run icon (see Figure D.2). The output appearsin the Command Window, and what is computed is shown in Figure D.4. The green commentline was typed directly into the Command Window after the program was run (this is usefulfor annotating the output when it is to be submitted as homework).

Figure D.4: Output from the ss.m file, along with a comment added afterward.

4

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.2.1 Printing

What is considered next are ways to print MATLAB files as well as the output.

m-file: The easiest way is the most basic. In particular, m-files are simple text documentsand these are easily printable on any computer system. This will not include thecolorized text seen in the Editor, and to have this you can use the Print icon in theMATLAB tool bar (see Figure D.2). A useful alternative, if you use LaTeX, is to usethe matlab-prettifier package. An example is given in the figure below, which containsthe LaTeX commands to print ss.m. Note that it reads the m-file, which is located bypathname (line 7), and produces a LaTeX version. Moreover, it’s possible to includetext in the document, which is useful for producing reports or homework writeups.

Command Window : The most basic method is to cut and paste the output into a textdocument. Many of the data tables in the textbook were constructed this way. Anotherapproach is to use the keystrokes usually used for printing (this also works for printinga m-file when in the Editor). What you get in this case is a full page, large format,printout of the output. If you want something more like what is shown in Figure D.3,then using a screen shot and an image editing program are probably the easiest to use.

Output : As illustrated in Figures D.3 and D.4, the fprintf command can be used to generateformatted output in the Command Window. It’s possible to write it to a text file instead(which are easily printable as well as editable). Assuming the name of the text file isdata.txt, then the commands shown in the figure below will work. Specifically, the fileis created (line 3), written into (line 13), and then closed (line 16).

5

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

MATLAB has a command for what is referred to as publishing. This allows for di↵erentformats, and control over what is printed. For example, in the Command Window, if youenter the command publish('ss.m','pdf') you obtain a pdf file containing a copy of the m-fileas well as the output from running the code. A portion of the page is shown in Figure D.5.There are numerous variations on this. As examples,

publish('ss.m','format','pdf','evalCode', false)

will produce a pdf file with no output, while

publish('ss.m','format','pdf','showCode', false)

will produce a pdf file with no m-file. To find out more about what formats are supported,and some of the options available, the help pages for publish and Publishing MATLAB Code

should be consulted.

Figure D.5: Portion of page produced using command publish('ss.m','pdf').

6

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.3 Basic Plotting

A basic m-file, named p.m, that plots y = cos(x) for 0 x 2⇡ is shown in the top rowin Figure D.6. To compute the curve, 100 points are used along the x-axis. The fact isthat the resulting plot is rather poor, and unacceptable for publication. For example, thetext is almost unreadable, and the curve is very light. This is easily fixed, and the modifiedfile, named pp.m, is shown in second row of Figure D.6. What was done was to change theline width for the curve (line 14), and to change the font properties used for labeling (line20). There is considerable flexibility to modify the plot parameters, and the help pages forthe plot command should be consulted. Also, in terms of the font size used in a plot, itis worth knowing that in publishing it is generally expected that the font size in the plotapproximately matches the size used in the text.

0 1 2 3 4 5 6 7x-axis

-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

y-axis

0 1 2 3 4 5 6 7x-axis

-1

-0.5

0

0.5

1

y-axis

Figure D.6: The commands on the left produce the plot on the right.

7

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.3.1 Legends

One additional situation worth illustrating concerns plots with multiple curves, and the asso-ciated legend required in the plot. An example of this is given in Figure D.7, where y = cos(x)and Y = e

�x/10 + x

1/5 are plotted for 0 x 2⇡. The file in this case is named ppp.m.What has been required is the hold command (line 16), the new plot command (line 17), andthe legend command (line 22). For readability, the font properties used in the legend havebeen modified (line 25).

0 1 2 3 4 5 6 7x-axis

-1

-0.5

0

0.5

1

y-ax

is

cos(x) e-x/10 - x1/5

Figure D.7: The commands on the top produce the plot on the bottom.

8

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.3.2 Saving and Printing Plots

It is recommended that before printing that you first save the plot. On the plot toolbar, underFile, there is a Save as option. After selecting this, you will be given the opportunity to selectthe format, as well as the name and location of the plot file. It is strongly recommended thatyou pick the EPS (*.eps) format. The reason is that it uses vector graphics, which meansthe image is scalable and capable of producing high resolution plots no matter what size youneed. As an illustration of this, the plot in Figure D.6 was saved using four di↵erent formats:eps, png, ti↵, and jpg. Each saved image was then opened, magnified, and the term x

1/5

in the legend was isolated and printed. The results are shown in Figure D.8. As expectedthe eps format is (clearly) superior to the others. Note that the Portable Document Format(*.pdf) format, also available, has the same high resolution capability as eps. The drawbackto this is that MATLAB uses an entire page for the plot, which limits embedding it into adocument or text file (as was done in Figures D.6 and Figures D.7).

As a tip, before saving the plot you might consider what relative dimensions you want(wider versus taller, etc). You can resize the plot window with the mouse, and the resizedversion is the one that will be saved.

Figure D.8: The x

1/5 term from Figure D.6 using eps (upper left), png (upper right), ti↵(lower left), and jpg (lower right) format.

9

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.4 If/Else/Break/Return

Conditionals are often needed, and can involve a wide variety of conditions or outcomes. Thisrequires knowing how relational and logical operators are written. Examples of some of themore often used possibilities are illustrated in the figure below. For more information aboutthese, look at relational operations and logical operations in MATLAB’s help pages.

generate some random integers

compute f if x > y

compute g if x � y and z = 1

otherwise, compute g if x 6= 2 or y z

otherwise, use this formula for g

if x < 5 stop computing and leave function

otherwise, if x < w then leave the for-loopand go to next command (line 30)

A few additional comments are in order. First, in the compound version (as in lines 13-19)it is possible to have multiple elseif conditions, and to not have an else condition. It isalso possible to have more than two tests for an if or elseif condition. If this is done, it’simportant to group the tests based on what is being required. For example, the tests

x � y or (x ⇤ y > 50 and z > 8)

can produce a di↵erent result from

(x � y or x ⇤ y > 50) and z > 8.

Finally, as the latter tests indicate, it is possible to have arithmetic expressions as part of atest.

10

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.5 Function Programs

The first line of the m-file ss.m, shown in Figure D.3, is function ss. The other m-files thathave been considered begin in a similar manner. The reason for doing this is that by declaringit a function program, all of the variables that are defined in the program are kept separatefrom other calculations that have been, or will be, done by MATLAB in the Command

Window. What is considered now is how to pass information between function programs,and to consider some of the reasons why you might want to do this.

Consider the secant method to solve f(x) = 0, which according to (2.24), gives rise to theequation

x

i+1 = x

i

� f(xi

)(xi

� x

i�1)

f(xi

)� f(xi�1)

, for i = 1, 2, · · · .

A function program for this is shown in the figure below (the algorithm is a modified versionof the one appearing in Table 2.6). It is not necessary to understand the various steps in

this program, other than it requires (in lines 4 and 9) the evaluation of f(x). This is goingto be done using another function program, and we want the value to be accessible to oursecant program. As an example, suppose f(x) = 3 cos(2⇡x)�4x. The corresponding functionprogram is shown below. The only remaining question is, where does this second function

go? Some like one function per m-file, and so they would put it in a file named f.m. It is alsopossible to include it at the end of the m-file that contains the secant1 function. The lattermethod is used with many of the m-files included with the textbook because it results in aself-contained file. In doing this, the first function is the main function, and is the one thatMATLAB associates with the file name. Subsequent functions in the m-file are called localfunctions and they are only available to the other functions within that file.

If the commands in the secant1 function are run, then the output will be printed in theCommand Window by the fprintf command (line 11 in secant1.m).

To illustrate another possibly, suppose we want to have a general purpose secant solver.The idea is that the user would provide the f.m file and the two starting values xa and xb,then find the solution by issuing the command secant2(xa,xb). This requires a few small

11

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

adjustments to secant1.m, and the result is shown in the figure below (the modified file isnamed secant2.m). If one takes xa = 0 and xb = 0.5, then in the Command Window they

would enter the command: x=secant2(0,0.5). In this way the xa and xb are passed to thesecant2 function, and the computed value for the solution is passed back to the Command

Window.

The m-files discussed above can be printed easily using the print icon (or associatedkeystrokes) described at the beginning of Section D.2.1. It is also possible to use the publish

command, although this requires using some options when applied to secant2.m. In this case,this can be done by issuing the command:

publish('secant2.m', struct('codeToEvaluate', 'x=secant2(0,0.5)', 'format','pdf'))

It appears that for the publish command to include the function for f(x), it is necessary toinclude it in the m-file secant2.m (rather than have it as a separate stand alone m-file).

For more information about functions and what can be done with them, see the MATLABhelp pages function and Create Functions in Files.

12

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

D.6 Entering Matrices and Vectors

Generally, the problems solved numerically are large enough that entering matrices and vec-tors by hand is impractical. Instead, for-loops or specialized commands are employed. Whatis described below are some of the ways to do this.

The most versatile way to enter a matrix is using nested for-loops. To illustrate, for then⇥m Vardermonde matrix V in Section 8.3, V

ij

= (1/i)j�1. In MATLAB, assuming n andm have been specified, this can be entered using the commands shown in the figure below.

This works for all matrices, with line 3 changed accordingly. Vectors can be entered similarly,using a single for-loop. What needs to be done is to indicate whether it is a column or rowvector. To illustrate, suppose the ith entry in a vector x is x

i

= 1/i. How to enter this as acolumn or row vector is shown in the figure below (it is assumed n has been specified). Forother vectors, line 3 would change accordingly.

Figure D.9: Left: commands to enter a column vector. Right: commands to enter a rowvector.

For a matrix with particular patterns in its entries, it is possible to use some of thespecialized commands available in MATLAB. Of particular interest are the following matrixgenerating commands:

ones(n,m): This is an n⇥m matrix consisting of all ones.

zeros(n,m): This is an n⇥m matrix consisting of all zeros.

eye(n,m): This is an n⇥m matrix with ones along the main diagonal, and zeros elsewhere.

diag(v,k): This creates a zero matrix except that the vector v is placed on the kth diagonal(with k = 0 for main diagonal, k = 1 for the superdiagonal, k = �1 for the subdiagonal,etc). Note that the size of the resulting matrix depends on the size of v and the valueof k.

13

Introduction to Scientific Computing and Data Analysis by M. Holmes (Springer, 2016)

An an example, a tridiagonal matrix can be written as follows (it is assumed n is specified):

0

BBBBB@

2 11 2 1

. . .. . .

. . .

11 2

1

CCCCCA=

0

BBBBB@

2 00 2 0

. . .. . .

. . .

00 2

1

CCCCCA+

0

BBBBB@

0 01 0 0

. . .. . .

. . .

01 0

1

CCCCCA+

0

BBBBB@

0 10 0 1

. . .. . .

. . .

10 0

1

CCCCCA

= 2 ⇤ eye(n, n) + diag(ones(n� 1, 1),�1) + diag(ones(n� 1, 1), 1)

The above formula might qualify for “advanced MATLAB,” in the sense that most casualusers would not know to use it. However, there is an alternative that most anyone under-stands. This involves using a single for-loop, and the commands are given in the figure below.The single line if conditionals (lines 3 and 4) are used just to show this is possible (versusthe more usual multline versions shown in Section D.4).

D.6.1 Row and Column Manipulation

An often useful command uses the colon (:) to access any particular row or column of amatrix. It is used in basically the same way that it is used in a for-loop, and in the figurebelow some of the possibilities are illustrated. The big di↵erence is when the colon is usedby itself (as in lines 4 and 6), which means that all possible index values are used.

generate a random n⇥m matrix

vector x is formed using the third column of A

set the second row of A to all ones

in the fifth column of A, set rows 2, 3, 4 to zero

the vector y is formed from the fourth row ofA, using column entries, 1, 3, 5

14