Docsity

Introduction to MATLAB for Numerical Computation, Exams of Applied Mathematics

Toggle sidebar
bg1
1. Introduction to MATLAB
MATLAB is an interactive, numerical computation program. It has powerful built-in routines that
enable a very wide variety of computations. It also has easy to use graphics commands that make the
visualization of results immediately available. In some installations MATLAB will also have a Symbolic
Toolbox which allows MATLAB to perform symbolic calculations as well as numerical calculations. In
this chapter we will describe how MATLAB handles simple numerical expressions and mathematical
formulas.
MATLAB is available on almost every computer system. Its interface is similar regardless of the
system being used. We will assume that you have sufficient understanding of your computer to start up
MATLAB and that you are now faced with a window on your computer which contains the MATLAB
prompt1,>>, and a cursor waiting for you to do something. This is called the MATLAB Command
Window, and it is time to begin.
Numerical Expressions
In its most elementary use, MATLAB is an extremely powerful calculator, with many built-in func-
tions, and a very large and easily accessible memory. Let’s start at the very beginning. Suppose you want
to calculate a number such as 12.3(48.5+342
39 ). You can accomplish this using MATLAB by entering
12.3*(48.5+342/39). Try it. You should get the following:
>> 12.3*(48.5+342/39)
ans =
704.4115
Notice that what you enter into MATLAB does not differ greatly from what you would write on a
piece of paper. The only changes from the algebra that you use every day are the different symbols used
for the algebraic operations. These are standard in the computer world, and are made necessary by the
unavailability of the standard symbols on a keyboard. Here is a partial list of symbols used in MATLAB.
+addition -subtraction
*multiplication ^exponentiation
/right division \left division
While +and −have their standard meanings, *is used to indicate multiplication. You will notice
that division can be indicated in two ways. The fraction 2
3can be indicated in MATLAB as either 2/3 or
as 3\2. These are referred to as right division and left division, respectively.
>> 2/3
ans =
0.6667
>> 3\2
ans =
0.6667
1In the narrative that follows, readers are expected to enter the text that appears after the command
prompt (>>). You must press the Enter or Return key to execute the command.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Introduction to MATLAB for Numerical Computation and more Exams Applied Mathematics in PDF only on Docsity!

1. Introduction to MATLAB

MATLAB is an interactive, numerical computation program. It has powerful built-in routines that enable a very wide variety of computations. It also has easy to use graphics commands that make the visualization of results immediately available. In some installations MATLAB will also have a Symbolic Toolbox which allows MATLAB to perform symbolic calculations as well as numerical calculations. In this chapter we will describe how MATLAB handles simple numerical expressions and mathematical formulas.

MATLAB is available on almost every computer system. Its interface is similar regardless of the system being used. We will assume that you have sufficient understanding of your computer to start up MATLAB and that you are now faced with a window on your computer which contains the MATLAB prompt^1 , >>, and a cursor waiting for you to do something. This is called the MATLAB Command Window, and it is time to begin.

Numerical Expressions

In its most elementary use, MATLAB is an extremely powerful calculator, with many built-in func- tions, and a very large and easily accessible memory. Let’s start at the very beginning. Suppose you want to calculate a number such as 12. 3 ( 48. 5 + 34239 ). You can accomplish this using MATLAB by entering 12.3*(48.5+342/39). Try it. You should get the following:

12.3*(48.5+342/39) ans =

Notice that what you enter into MATLAB does not differ greatly from what you would write on a piece of paper. The only changes from the algebra that you use every day are the different symbols used for the algebraic operations. These are standard in the computer world, and are made necessary by the unavailability of the standard symbols on a keyboard. Here is a partial list of symbols used in MATLAB.

  • addition - subtraction
  • multiplication ^ exponentiation / right division \ left division

While + and − have their standard meanings, * is used to indicate multiplication. You will notice that division can be indicated in two ways. The fraction 23 can be indicated in MATLAB as either 2/3 or as 3\2. These are referred to as right division and left division, respectively.

2/ ans =

3
ans =

(^1) In the narrative that follows, readers are expected to enter the text that appears after the command

prompt (>>). You must press the Enter or Return key to execute the command.

Exponentiation is quite different in MATLAB; it has to be, since MATLAB has no way of entering superscripts. Consequently, the power 4 3 must be entered as 4^3.

4^ ans = 64

The order in which MATLAB performs arithmetic operations is exactly that taught in high school algebra courses. Exponentiations are done first, followed by multiplications and divisions, and finally by additions and subtractions. The standard order of precedence of arithmetic operations can be changed by inserting parentheses. For example, the result of 12.3*(48.5+342)/39 is quite different than the similar expression we computed earlier, as you will discover if you try it.

MATLAB allows the assignment of numerical values to variable names. For example, if you enter

x = 3 x = 3

then MATLAB will remember that x stands for 3 in subsequent computations. Therefore, computing 2.5*x will result in

2.5*x ans =

You can also assign names to the results of computations. For example,

y = (x+2)^ y = 125

will result in y being given the value ( 3 + 2 )^3 = 125.

You will have noticed that if you do not assign a name for a computation, MATLAB will assign the default name ans to the result. This name can always be used to refer to the results of the previous computation. For example:

2+

ans = 5

ans/ ans = 1

MATLAB has a few preassigned variables or constants. The constant π = 3. 14159 ... is given the name pi.

pi ans =

The Exponential and Logarithm Functions

exp(x) The exponential of x, i.e. e x^. log(x) The natural logarithm of x, i.e. ln(x) log10(x) The logarithm of x to base 10, i.e. log 10 (x).

The Hyperbolic Functions

sinh(x) The hyperbolic sine of x, i.e. sinh(x). cosh(x) The hyperbolic cosine of x, i.e. cosh(x). tanh(x) The hyperbolic tangent of x, i.e. tanh(x). coth(x) The hyperbolic cotangent of x, i.e. coth(x). sech(x) The hyperbolic secant of x, i.e. sech(x). csch(x) The hyperbolic cosecant of x, i.e. csch(x).

The Inverse Hyperbolic Functions

asinh(x) The inverse hyperbolic sine of x, i.e. sinh−^1 (x). acosh(x) The inverse hyperbolic cosine of x, i.e. cosh−^1 (x). atanh(x) The inverse hyperbolic tangent of x, i.e. tanh−^1 (x). acoth(x) The inverse hyperbolic cotangent of x, i.e. coth−^1 (x). asech(x) The inverse hyperbolic secant of x, i.e. sech−^1 (x). acsch(x) The inverse hyperbolic cosecant of x, i.e. csch−^1 (x).

For a more extensive list of the functions available, see the MATLAB User’s Guide, or MATLAB’s online documentation.^2 All of these functions can be entered at the MATLAB prompt either alone or in combination. For example, to calculate sin(x) − ln(cos(x)), where x = 6, we simply enter

x = 6 x = 6

sin(x)-log(cos(x)) ans = -0.

Take special notice that ln(cos(x)) is entered as log(cos(x)). The function log is MATLAB’s repre- sentation of the natural logarithm function.

Output Format

Up to now we have let MATLAB repeat everything that we enter at the prompt. Sometimes this is not useful, particularly when the output is pages in length. To prevent MATLAB from echoing what we

(^2) MATLAB comes with extensive online help. Typing helpdesk at the MATLAB prompt should open

MATLAB’s helpdesk in a separate browser. You can also access MATLAB’s standard help files by typing help at the MATLAB prompt. For a list of MATLAB’s elementary functions, type help elfun at the MATLAB prompt.

tell it, simply enter a semicolon at the end of a command. For example, enter

q=7;

and then ask MATLAB what it thinks q is by entering

q q = 7

If you use MATLAB to compute cos(π), you get

cos(pi) ans =

In this case MATLAB is smart enough to realize that the answer is an integer and it displays the answer in that form. However, cos( 3 ) is not an integer, and MATLAB gives us -0.9900 as its value. Thus, if MATLAB is not sure that a number is an integer, it displays five significant figures in its answer. As another example, 1.57 is very close to π/2, and cos(π/ 2 ) = 0. MATLAB gives us

cos(1.57) ans = 7.9633e-

This is an example of MATLAB’s exponential, or scientific notation. It stands for 7. 9633 × 10 −^4 , or 0 .00079633. In this case MATLAB again displays five significant digits in its answer. All of these illustrate the default format, which is called the short format. It is important to realize that although MATLAB only displays five significant digits in the default format, it is computing the answer to an accuracy of sixteen significant figures.

There are several other formats. We will discuss two of them. If it is necessary or desirable to have more significant digits displayed, enter format long at the MATLAB prompt. MATLAB will then display about sixteen significant digits. For example,

format long cos(1.57) ans = 7.963267107332634e-

There is another output format which we will find useful. If you enter format rat, then all numbers will be shown as rational numbers. This is called the rational format. If the numbers are actually irrational, MATLAB will find a very close rational approximation to the number.

cos(1.57) ans = 47/

The rational format is most useful when you are working with numbers you know to be rational. After using a different format, you can return to the standard, short format by entering format short.

Note that several MATLAB commands can be placed on a single line, separated by commas, or semicolons, should you desire to suppress the output. The ease with which MATLAB handles complex numbers has one drawback. There is at least one case where the answer is not the one we expect. Use MATLAB to calculate (− 1 )^1 /^3. Most people would expect the answer −1, but MATLAB gives us

(-1)^(1/3) ans = 0.5000 + 0.8660i

At first glance this may seem strange, but if you cube this complex number you do get −1. Consequently MATLAB is finding a complex cube root of −1, while we would expect a real root. The situation is even worse, since in most of the cases where this will arise in this manual, it is not the complex cube root we want. We will want the cube root of −1 to be −1. However, this is a price we have to pay for other benefits. For MATLAB to be so flexible that it can calculate roots of arbitrary order of arbitrary complex numbers, it is necessary that it should give what seems like a strange answer for the cube root of negative numbers. In fact the same applies to any odd root of negative numbers. What we need is a way to work around the problem. Notice that if x < 0, then x = − 1 × |x|, and we can find a negative cube root as − 1 × |x|^1 /^3. Here we are taking the real cube root of the positive number |x|, and MATLAB does that the way we want it done. But suppose the situation arises where we do not know beforehand whether x is positive or negative. What we want is

x^1 /^3 =

|x|^1 /^3 , if x > 0; 0 , if x = 0; − 1 × |x|^1 /^3 , if x < 0. To write this more succinctly we use the signum function sgn(x) (in MATLAB it is denoted by sign(x)). This function is defined to be

sgn(x) =

{ (^1) , if x > 0; 0 , if x = 0; − 1 , if x < 0. Thus, in all cases we have x = sgn(x) |x|, and the real cube root is

x^1 /^3 = sgn(x) |x|^1 /^3.

In MATLAB, we would enter sign(x)*abs(x)^(1/3).

Recording Your Work

It is frequently useful to be able to record what happens in a MATLAB session. For example, in the process of preparing a homework submission, it should not be necessary to copy all of the output from the computer screen. You ought to be able to do this automatically. The MATLAB diary command makes this possible. For example, suppose you are doing your first homework assignment and you want to record what you are doing in MATLAB. To do this, choose a name, perhaps hw1, for the file in which you wish to record the output. Then enter diary hw1 at the MATLAB prompt. From this point on, everything that

appears in the Command Window will also be recorded in the file hw1. When you want to stop recording enter diary off. If you want to start recording again, enter diary on. The file that is created is a simple text file. It can be opened by an editor or a word processing program and edited to remove extraneous material, or to add your comments. You can use the MATLAB editor for this process. To access it, first be sure you have stopped the editing process by executing diary off. Next, either click on the open file in the Toolbar, or select Open file from the Edit menu. The file selection window that opens is set to display only MATLAB files, so the text diary file will not be visible. Click on the Files of type: popup menu and select All Files. Then select the name of your diary file. You will now be able to make any changes you want in the file. You will also be able to print the file to get a hard copy.

To open your diary file, or any other file you create with MATLAB, you will have to know where it is stored on your computer. This means that you will have to understand the directory structure on your computer. (We are using directory as a synonym of file folder.) Your diary file is saved in the current directory. In MATLAB 6, the current directory is displayed in a small box at the top of the command window. Next to it there is a button with three dots (an ellipsis) on it. Clicking this button will open a new window containing the directory tree of your computer. You can make any directory the current directory by selecting it from the directory tree.

Different operating systems provide different ways of handling files and directories. However, it is possible to do a lot of file handling entirely within MATLAB. For this purpose MATLAB uses a combination of UNIX and DOS commands. You can find the name of the current directory by using the command pwd. The response will be the full address of the current directory in the language of your operating system. You can obtain a list of the files in the current directory with the commands ls or dir. You can change directories with the commands cd or chdir. You can make a new directory with the command mkdir. We suggest that you use the help command 3 to find out more, and experiment with these commands to learn what they do in your system.

Exercises

  1. Use the standard procedure on your computer system to create a folder named mywork. In MATLAB change to this folder either by using the command cd at the MATLAB prompt or by clicking the ellipsis (... ) button next to the Current Directory edit box on your MATLAB toolbar and browsing to the folder mywork. Look at the Current Directory edit box to be sure that mywork is the current directory. You can also use the command pwd at the MATLAB prompt. Clear the command window with the command clc, then clear your workspace of all variables with the command clear. Start a diary session with diary hmwk1. Read Chapter 1 (Introduction to Matlab) of this manual again, but this time enter each of the commands in the narrative at the MATLAB prompt as you read. When you are finished, enter the command diary off. Open the file hmwk1 in your favorite editor or word processor (or open it in Matlab’s editor by typing edit hmwk1 at the MATLAB prompt). Edit and correct any mistakes that you made. Save and print the edited file and submit the result to your instructor.

(^3) For example, type help cd to obtain help on using the command cd.

the interval [− 2 π, 2 π], as is xe−x

2 , then ezplot chooses a smaller interval. If the default interval does not please you, you can choose your own. For example, execute

ezplot('sin(x)',[0,8*pi])

to plot the sine function over the interval [0, 8 π].

Example 1. The initial value problem y′^ = y + t with y( 0 ) = 0 has the solution y(t) = e t^ − t − 1_. Plot this solution over the interval_ 0 ≤ t ≤ 2.

This can be done with the single command ezplot('exp(t)-t-1',[0,2]). The command ezplot can also plot curves that are defined implicitly or parametrically. To learn about these features execute help ezplot. This command also illustrates the use of the command help. Whenever you run across a command you do not understand, use the help command. It will provide you with the information you need.

Example 2. The solution to the initial value problem y′^ = − 2 t/( 3 y^2 + 2 y + 1 ) with y( 0 ) = 0 satisfies the implicit relationship y^3 + y^2 + y + t^2 = 0. Plot the solution over the interval − 2 ≤ t ≤ 2.

If you execute the command ezplot('y^3+y^2+y+t^2 = 0'), you will get the plot of the solution shown in Figure 2.3. Notice that by default the solution is plotted over − 2 π ≤ x ≤ 2 π. The important part of the solution would be better portrayed if the t-axis were reduced to − 2 ≤ t ≤ 2 and the y-axis were reduced to − 2 ≤ y ≤ 1. This can be done with the command ezplot('y^3+y^2+y+t^2',[-2, 2, -2, 1]). The result is shown in Figure 2.4. It is very typical that our first attempt is not completely satisfactory. Do not be afraid to redo a plot to make it look better.

−6 −4 −2 0 2 4 6

−

−

−

0

2

4

6

t

y

y^3 +y 2 +y+t^2 = 0

−2 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2

−1.

−

−0.

0

1

t

y

y 3 +y 2 +y+t^2 = 0

Figure 2.3. The solution in Example 2. Figure 2.4. The solution in a smaller plot area.

The vector [-2, 2, -2, 1] that appears in the ezplot command means that the plot area will be limited by − 2 ≤ t ≤ 2 and − 2 ≤ y ≤ 1. This vector is referred to as the axis. You can discover

the axis of the current plot by executing axis on the command line. Execute help axis to learn more about this versatile command. For example, the same reduction of plot area can be accomplished with the command axis([-2, 2, -2, 1]) after the plot in Figure 2.3 was done. If you own the Symbolic Toolbox, an add-on product to MATLAB, the command ezplot provides an excellent way to get a quick plot of the solution of an initial value problem.

Example 3. Graph the solution of y′^ − y = e−t^ cos 3t, with y( 0 ) = 1.

Enter the command

dsolve('Dy - y = exp(-t)cos(3t)','y(0) = 1') ans = -2/13exp(-t)cos(3t)+3/13sin(3t)exp(-t)+15/13*exp(t)

Then the command

ezplot(ans)

will provide a plot of the solution. We discuss the Symbolic Toolbox in Chapter 10.

Matrices and Vectors in MATLAB

To use the plot command effectively it is necessary to know a little about how MATLAB works. A powerful feature of MATLAB is that every numerical quantity is considered to be a complex matrix!^1 For those of you who do not already know, a matrix is a rectangular array of numbers. For example,

A =

[

1 π

√ −^1

]

is a matrix with 2 rows and 3 columns. If you want to enter the matrix A into MATLAB proceed as follows:

A = [1,pi,sqrt(-1);sqrt(2),4,0] A = 1.0000 3.1416 0 + 1.0000i 1.4142 4.0000 0

Note that commas are used to separate the individual elements in a row, and semicolons are used to separate the rows of the matrix. You can also use spaces to separate (delimit) the entries in a row. Thus, the command A = [1 pi sqrt(-1);sqrt(2) 4 0] can be used to enter A into MATLAB. The size of a matrix is the number of rows and columns. For example,

size(A) ans = 2 3 (^1) A matrix whose entries are complex numbers.

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

A =

B =

C =

You will notice that each element of the matrix C is sum of the corresponding elements in the matrices A and B. The same is true for the difference of two matrices. Try C-A, and see what you get (you should get B). You can multiply or divide any matrix by a scalar.

v = ones(1,5); w = 4*v, z = v/ w = 4 4 4 4 4 z = 0.5000 0.5000 0.5000 0.5000 0.

While multiplication and division by scalars are standard parts of matrix algebra, the addition of a scalar to, or the subtraction of a scalar from a matrix are not standard algebra. However, they are allowed in MATLAB. Try

m = v - 3, a = v + 4 m = -2 -2 -2 -2 - a =

5 5 5 5 5

MATLAB’s transpose operator (a single apostrophe) changes a column vector into a row vector (and vice-versa).

u = [1;2], v = u' u = 1 2 v = 1 2

Actually, .' is MATLAB’s transpose operator and ' is MATLAB’s conjugate transpose operator. Enter A = [1+i,-2;3i,2-i], then type A' and view the results. Note that rows of A have become columns, but each entry has been replaced with its complex conjugate. Type A.' to appreciate the difference. If each entry of a matrix is a real number, then it doesn’t matter whether you use ' or .'.

Array Operations and Array Smart Functions

MATLAB has built-in, element-by-element, operations for other mathematical operations on matrices For example, should you need to multiply two vectors on an element-by-element basis, use MATLAB’s .* operator.

v = [1,2,3,4], w = [5,6,7,8], u = v.*w v = 1 2 3 4 w = 5 6 7 8 u = 5 12 21 32

If you look closely, you will see that u is a vector of the same size as v and w, and that each element in u is the product of the corresponding elements in v and w. This operation is called array multiplication , and MATLAB’s symbol for it is .*, not . MATLAB uses * for matrix multiplication, which is quite different from array multiplication. Try entering vw and see what happens. We will explain matrix multiplication in Chapter 11. There are other array operations. All of them act element-by-element. Try v./w and w./v. This is array right division. Then try v.\w and w.\v, and compare the results. This is called array left division. There is one other array operation — array exponentiation. This is also an element-by-element operation. The operation A.^2 results in every element of the matrix A being raised to the second power. For example, if A = [1,2;3,4], the command

A = [1,2;3,4], B = A.^ A = 1 2 3 4 B = 1 4 9 16

raises each entry in A to the second power. The command A^2 is equivalent to AA, which gives an entirely different result. Try it and see. For all array operations it is required that the matrices have exactly the same size. You might try [1,2;3,4].[1;1] to see what happens when they are not. The built-in MATLAB functions, which we discussed briefly in Chapter 1, are all designed to be array smart. This means that if you apply them to a matrix, the result will be the matrix obtained by applying the function to each individual element. For example:

theta = [0,pi/2,pi,3pi/2,2pi], y = cos(theta) theta = 0 1.5708 3.1416 4.7124 6. y = 1.0000 0.0000 -1.0000 0.0000 1.

This is an extremely important feature of MATLAB, as you will discover in the next section.

Notice that the plot in Figure 2.5 is kinky. This is because we plotted too few points before MATLAB connected the dots with straight lines. If we use enough points we get a smooth looking curve. For example, the commands

t = 0:0.05:1; y = t.^3; plot(t,y), shg

produced the graph in Figure 2.6. This time there are 21 points, and the curve appears smooth. Notice that multiple commands can be entered on a single command line if they are separated with commas and/or semicolons. The command shg stands for “show the graph,” and it brings the current figure window 4 to the front. It is a good idea to add shg to plot commands on the command window.

Example 4. Use the plot command to graph f (x) = xe−x

2 over the interval [− 2 , 2].

To accomplish this task, we need two MATLAB vectors. First, we need a vector x containing a large number of values between −2 and 2. We can do this with the command x = -2:0.1:2. Next we need a vector y containing the values of f (x) = xe−x

2 at the points in x. This can be accomplished using the array operations. The operation .^ works element by element, so the vector x.^2 contains the squares

of the values in x. Since MATLAB functions are array smart, exp(-x.^2) contains the values of e−x

2

for each of the entries of x. Finally, since .* is an array operation, x.*exp(-x.^2) contains the values

of f (x) = xe−x

2 for the entries in x. Thus the commands

x = -2:0.1:2; y = x.*exp(-x.^2); plot(x,y), shg

will produce the desired graph. Executing the command grid produces Figure 2.7.

−3 −2 −1 0 1 2 3

−0.

−0.

−0.

−0.

−0.

0

−30 −20 −10 0 10 20 30

−

−

−

−

−

0

5

10

15

20

25

Figure 2.7. The graph for Example 4. Figure 2.8. The parametric curve in Exam- ple 5.

(^4) If several figure windows are open, the last one visited is the “current figure window.”

Parametric plots. Notice that in Example 4 we used the command plot(x,y), where x and y were vectors of the same size. This command all by itself cares not where the two vectors came from. For any two vectors of the same size, the command will plot the (x, y) pairs and connect them with line segments. We can utilize this to produce parametric plots.

Example 5. Plot the parametric curve defined by t → (t cos t, t sin t) for 0 ≤ t ≤ 8 π.

We start with the command t = linspace(0,8pi,200), which produces 200 equally spaced points^5 between 0 and 8π. Then x = t.cos(t), and y = t.*sin(t) produce the corresponding values of the components of the desired curve. Finally, plot(x,y), shg produces the plot. To summarize, we use the commands

t = linspace(0,8pi,200); x = t.cos(t); y = t.*sin(t); plot(x,y), shg

Curves in Three Dimensions. Three dimensional plots require the use of plot3 instead of plot, but otherwise the method is unchanged. The commands

t = linspace(0,20); x = cos(t); y = sin(t); z = t; plot3(x,y,z), shg xlabel('x = cos t'); ylabel('y = sin t'); zlabel('t')

produce the helix in Figure 2.9. By default, the command linspace(a,b) produces a vector of 100 evenly spaced point between a and b.

−1 −0.

0 0.

1

−

−0.

0

1

0

5

10

15

20

y = sin t x = cox t

t

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

−0.

−0.

−0.

−0.

0

yy s

Figure 2.9. The spiral curve with x = cos t, y = sin t, and z = t.

Figure 2.10. Plots of y and ys.

(^5) Type help linspace for more information on using this command

produces the legend. It is only necessary to list the names in the order the graphs were produced. Notice that although entered as y_s, the label in the legend is subscripted.

A second solution to the problem of adding graphs to a figure involves the commands hold on and hold off. The command hold on tells MATLAB to add subsequent plots to the existing figure, without erasing what is already there. The command hold off tells MATLAB to return to the standard procedure of erasing everything before the next plot. This means that hold on is in effect until a hold off command is executed. Thus, we could have used the commands

plot(t,y) hold on plot(t,y_s,'--'), shg hold off

to produce the plot in Figure 2.10.

A third way to plot two curves is to put the two sets of y-data into a matrix. The single command

plot(t,[y;y_s])

will cause the two curves to be plotted. The command [y;y_s] puts the two row vectors y and y_s into a matrix with two rows and as many columns as t. If A is a matrix with as many columns as t, then plot(t,A) will graph each row of A against t. A different color is automatically chosen for each curve.

Editing Graphics

MATLAB has extensive figure editing features. To use these make sure that the Figure Toolbar is visible by selecting View → Figure Toolbar.^6

To change the appearance of a curve, click on the selection tool (the arrow pointing up and to the left in the Toolbar). Then click on the curve to select it. Now right-click 7 on the curve to bring up a context menu. There are several choices, but the ones we are most interested in allow us to change the line-width, line-style, and color of the curve. The use of these is amply clear once you try them once. If you select Properties , you are provided with a Property Editor window that gives complete control over the line properties, including adding markers to the data points and all of the available marker properties.

The Property Editor can also be accessed through the Edit menu. To edit the properties of a curve, first make that curve the current object by clicking on it. Then select Edit → Current Object Properties .... There are also Property Editors for the Figure (the area around the graph) and the Axes (the axis lines and labels, together with the background of the graph). In each case selection opens a new window which gives you complete control over the appearance of the object chosen.

For more information about editing your graphs, select Help → Formatting Graphs in any figure window.

(^6) The notation View → Figure Toolbar means you should choose Figure Toolbar from the View

menu located on the current figure window. (^7) Here we are assuming you have a mouse with two or more buttons. If you use a Macintosh and have

only one button, use a control-click instead of a right-click.

Saving, Printing, and Exporting Your Plot

After learning how to plot graphs, you will want to print them. Simply use the print command in the File menu, or the print icon in the toolbar. Edit → Print Setup allows you to choose a printer and its properties and to choose between landscape or portrait output. Edit → Page Setup allows you to change many aspects of the printout.

To save a MATLAB figure to the clipboard, use the Edit → Copy Figure command. You will then be able to paste the figure into another document. If you need to save a copy of a MATLAB figure to a graphics file, use the File → Export command. You will be given the opportunity to choose from a large variety of graphics formats. The choices made using Edit → Page Setup affect the exported file, so some flexibility is available. It is possible to print what appears in the current figure window 8 to the default printer by simply entering print at the MATLAB prompt. In fact the print command provides many possibilities. Execute help print to explore them. For example, it is possible to export a figure to a graphics file using the print command at the command line. The command

print -deps junk.eps

will save the current figure as the encapsulated postscript file junk.eps in the current directory.

Script M-files

You will have noticed that producing a finished graphic in MATLAB requires the use of several commands entered at the command line. A finished graphic often requires several passes through these commands in order to get everything just right. Fortunately there is a way to get around the need to repeatedly enter a large list of commands as you improve on a graphic. It is possible to enter these commands into a text file, and execute all of them with one command. Such files are called M-files. M-files come in two types, each with its own features. The type to use in building a complicated graphic is a script M-file , and we will describe them in this chapter. In addition there are function M-files , which can be used, for example, to extend MATLAB ’s library of functions. We will discuss function M-files in Chapter 4.

Let’s start with a complicated graphing problem.

Example 7. In one figure, plot the solutions to the differential equation y′^ = y + t with initial conditions y( 0 ) = − 2 , − 1 , 0 , 1 , 2 over the interval 0 ≤ t ≤ 2_._

The general solution to the differential equation is y(t) = Ce t^ − t − 1. The initial condition is y( 0 ) = C − 1, so the constant satisfies C = y( 0 ) + 1. The graphs can be drawn using the techniques we have already discussed, but it is easy to make mistakes in executing all of the commands needed. Instead we will create a script M-file. To see how this is done, choose the menu item File–>New–>M-file. The built-in MATLAB editor 9 will open at a blank page. You can also call up the editor by executing the

(^8) MATLAB’s figure command allows you to create multiple figure windows. If you have several figure windows open, click any figure window with your mouse to make it the current figure window. (^9) Starting with version 5.2, MATLAB has built-in editor on every platform. Of course, it is not