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 functions, 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 multiplication right division ^ \ subtraction exponentiation 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/3 ans = 0.6667 >> 3\2 ans = 0.6667 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. 1 Exponentiation is quite different in MATLAB; it has to be, since MATLAB has no way of entering superscripts. Consequently, the power 43 must be entered as 4^3. >> 4^3 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 = 7.5000 You can also assign names to the results of computations. For example, >> y = (x+2)^3 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+3 ans = 5 >> ans/5 ans = 1 MATLAB has a few preassigned variables or constants. The constant π = 3.14159... is given the name pi. >> pi ans = 3.1416 2 The square root of −1 is i. >> sqrt(-1) ans = 0 + 1.0000i Engineers and physicists frequently use i to represent current, so they prefer to use j for the square root of −1. MATLAB is well aware of this preference. >> j ans = 0 + 1.0000i There is no symbol for e, the base of the natural logarithms, but this can be easily computed as exp(1). >> exp(1) ans = 2.7183 Mathematical Functions There is a long list of mathematical functions that are built into MATLAB. Included are all of the functions that are standard in calculus courses. Elementary Functions abs(x) sqrt(x) sign(x) The absolute value of x, i.e. √ |x|. The square root of x, i.e. x. The signum of x, i.e. 0 if x = 0, −1 if x < 0, and +1 if x > 0. The Trigonometric Functions sin(x) cos(x) tan(x) cot(x) sec(x) csc(x) The sine of x, i.e. sin(x). The cosine of x, i.e. cos(x). The tangent of x, i.e. tan(x). The cotangent of x, i.e. cot(x). The secant of x, i.e. sec(x). The cosecant of x, i.e. csc(x). The Inverse Trigonometric Functions asin(x) acos(x) atan(x) acot(x) asec(x) acsc(x) The inverse sine of x, i.e. arcsin(x) or sin−1 (x). The inverse cosine of x, i.e. arccos(x) or cos−1 (x). The inverse tangent of x, i.e. arctan(x) or tan−1 (x). The inverse cotangent of x, i.e. arccot(x) or cot−1 (x). The inverse secant of x, i.e. arcsec(x) or sec−1 (x). The inverse cosecant of x, i.e. arccsc(x) or csc−1 (x). 3 The Exponential and Logarithm Functions exp(x) log(x) log10(x) The exponential of x, i.e. ex . The natural logarithm of x, i.e. ln(x) The logarithm of x to base 10, i.e. log10 (x). The Hyperbolic Functions sinh(x) cosh(x) tanh(x) coth(x) sech(x) csch(x) The hyperbolic sine of x, i.e. sinh(x). The hyperbolic cosine of x, i.e. cosh(x). The hyperbolic tangent of x, i.e. tanh(x). The hyperbolic cotangent of x, i.e. coth(x). The hyperbolic secant of x, i.e. sech(x). The hyperbolic cosecant of x, i.e. csch(x). The Inverse Hyperbolic Functions asinh(x) acosh(x) atanh(x) acoth(x) asech(x) acsch(x) The inverse hyperbolic sine of x, i.e. sinh−1 (x). The inverse hyperbolic cosine of x, i.e. cosh−1 (x). The inverse hyperbolic tangent of x, i.e. tanh−1 (x). The inverse hyperbolic cotangent of x, i.e. coth−1 (x). The inverse hyperbolic secant of x, i.e. sech−1 (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.2388 Take special notice that ln(cos(x)) is entered as log(cos(x)). The function log is MATLAB’s representation 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. 4 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 = -1 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-004 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-004 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/59021 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. 5 Complex Arithmetic One of the nicest features of MATLAB is that it works as easily with complex numbers as it does with real numbers. The complex number z = 2 − 3i is entered exactly as it is written. >> z = 2-3i z = 2.0000 - 3.0000i Then if we enter w = 3 + 5i, we can calculate sums, products, and quotients of these numbers in exactly the same way we do for real numbers. For example, >> w = 3+5i; >> z*w ans = 21.0000 + 1.0000i and >> z/w ans = -0.2647 - 0.5588i Any of the arithmetic functions listed earlier can be applied to complex numbers. For example, >> y = sqrt(w) y = 2.1013 + 1.1897i and >> y*y ans = 3.0000 + 5.0000i Since y 2 = w, it is a square root of the complex number w. The reader might try cos(w) and exp(w). In particular, the reader might wish to verify Euler’s formula eiθ = cos(θ) + i sin(θ) for several values of θ, including θ = 2π, π, π/2. >> theta = pi; exp(i*theta), cos(theta) + i*sin(theta) ans = -1.0000 + 0.0000i ans = -1.0000 + 0.0000i 6 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 , if x > 0; 1/3 x = 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 1, if x > 0; sgn(x) = 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 7 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 command3 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. 8 2. Plotting in MATLAB MATLAB provides several methods for plotting the graphs of functions and more general curves. The easiest to use is what we will call EZ plotting, since it uses the command ezplot and its variants. While it is easy to use it lacks flexibility. We will briefly explain EZ plotting in the first section. The second method we will describe uses the commands plot and plot3. It provides more flexibility at the cost of some ease of use. It is the principal method used in this manual, so we will explain it in some detail. At the end of this chapter we will introduce MATLAB’s handle graphics. The use of handle graphics gives the user complete control over the graphic, but it is not so easily used. EZ plotting To plot the sine function in MATLAB, simply execute the command >> ezplot('sin(x)') The result is shown in Figure 2.1. You will notice that ezplot produces the plot of sin(x) over the interval [−2π, 2π ]. Next execute >> ezplot('x*exp(-x^2)') This time the plot, shown in Figure 2.2, is over an interval slightly bigger than [−2.5, 2.5]. 2 x exp(−x ) sin(x) 0.5 1 0.4 0.3 0.5 0.2 0.1 0 0 −0.1 −0.2 −0.5 −0.3 −0.4 −1 −0.5 −6 −4 −2 0 x 2 4 6 −2.5 −2 −1.5 −1 −0.5 0 x 0.5 1 1.5 2 2.5 Figure 2.2. Plot of xe−x . 2 Figure 2.1. Plot of sin x. Notice that you did not have to specify a plot interval. The command ezplot uses [−2π, 2π ] as the default interval over which to produce a plot. If the function is almost constant near the endpoints of 9 the interval [−2π, 2π], as is xe−x , then ezplot chooses a smaller interval. If the default interval does not please you, you can choose your own. For example, execute 2 >> 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) = et − 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 = −2t/(3y 2 + 2y + 1) with y(0) = 0 satisﬁes 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. 3 2 2 y +y +y+t = 0 6 1 4 0.5 2 0 0 y y y3+y2+y+t2 = 0 −2 −0.5 −1 −4 −1.5 −6 −6 −4 −2 0 2 4 −2 −2 6 t −1.5 −1 −0.5 0 0.5 1 1.5 2 t 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 10 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(3*t)','y(0) = 1') ans = -2/13*exp(-t)*cos(3*t)+3/13*sin(3*t)*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, √ 1 π −1 A= √ 2 4 0 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 1.4142 4.0000 0 + 1.0000i 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. 11 verifies that A has 2 rows and 3 columns. Two matrices are said to have the same size if they have the same number of rows and the same number of columns. Even single numbers in MATLAB are matrices. For example, >> a = 5; >> size(a) ans = 1 1 shows that MATLAB thinks that 5, or any other complex number, is a matrix with one row and one column. A vector is a list of numbers.2 It can be a vertical list, in which case it is called a column vector, or it can be a horizontal list, in which case it is called a row vector. Vectors are special cases of matrices, so √ you can enter the row vector v = [1, −5, π, −1] into MATLAB using the command v = [1,-5,pi,sqrt(-1)] or v = [1 -5 pi sqrt(-1)]. On the other hand, we can define a column vector with the command u = [1;2;3;4]. It is important to remember that MATLAB distinquishes between row and column vectors. In MATLAB, the length of a vector is the number of elements in the list. For example, the MATLAB length of each of the vectors u and v defined in the previous paragraph is 4. The MATLAB command length will disclose the length of any vector. Try length(u) and length(v). Notice that u and v have the same length, but not the same size, since u is a column vector and v is a row vector. This notion of length is not to be confused with the geometric length of a vector, defined to be the square root of the sum of the squares of the absolute values of the entries. MATLAB’s command for finding the geometric length of a vector is norm. For example, >> norm(v) ans = 6.0720 Addition, Subtraction, and Multiplication by Scalars If A and B are matrices of the same size, then they can be added together. For example, 2 The word vector is one of the most over used terms in mathematics and its applications. To a physicist or a geometer, a vector is a directed line segment. To an algebraist or to many engineers, a vector is a list of numbers. To users of more advanced parts of linear algebra, a vector is an element of a vector space. In this latter, most general case, a vector could be any of the above examples, a polynomial, a more general function, or an example of, quite literally, any class of mathematical objects which can be added together and scaled by multiplication. All too often the meaning in any particular situation is not explained. The result is very confusing to the student. When the word vector appears, a student should make a concerted effort to discover the meaning that is used in the current setting. When using MATLAB, the situation is clear. A vector is a list of numbers, which may be complex. 12 >> A = [1 2;3 4], B = [5,6;7,8], C = A + B A = 1 2 3 4 B = 5 6 7 8 C = 6 8 10 12 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/2 w = 4 4 4 4 4 z = 0.5000 0.5000 0.5000 0.5000 0.5000 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 -2 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 .'. 13 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 = v = 1 w = 5 u = 5 [1,2,3,4], w = [5,6,7,8], u = v.*w 2 3 4 6 7 8 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 v*w 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.^2 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 A*A, 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,3*pi/2,2*pi], y = cos(theta) theta = 0 1.5708 3.1416 4.7124 6.2832 y = 1.0000 0.0000 -1.0000 0.0000 1.0000 This is an extremely important feature of MATLAB, as you will discover in the next section. 14 Plotting in MATLAB Using the plot Command None of these array operations would be important if it were not so easy to create and use vectors and matrices in MATLAB. Here is a typical situation. Suppose we want to define a vector that contains a large number of equally spaced points in an interval [a, b]. MATLAB’s start:increment:finish construct allows you to generate equally spaced points with ease. For example, the command >> t = 0:0.2:1 t = 0 0.2000 0.4000 0.6000 0.8000 1.0000 generates numbers from 0 to 1 in increments of 0.2.3 The command y = t.^3 will produce a vector y with 6 entries, each the cube of the corresponding entry in the vector t. >> y = t.^3 y = 0 0.0080 0.0640 0.2160 0.5120 1.0000 We can get a rudimentary plot of the function y = t 3 by plotting the entries of y versus the entries of t. MATLAB will do this for us. The command >> plot(t,y) will produce a plot of y versus t in the current figure window. If no figure window exists, then the command plot will create one for you. MATLAB plots the 6 ordered pairs (t, y) generated by the vectors t and y, connecting consecutive ordered pairs with line segments, to produce an plot similar to the that shown in Figure 2.5. 1 1 0.9 0.9 0.8 0.8 0.7 0.7 0.6 0.6 0.5 0.5 0.4 0.4 0.3 0.3 0.2 0.2 0.1 0.1 0 0 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Figure 2.5. A simple plot 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Figure 2.6. A simple plot with refined data. 3 If you omit the increment, as in t = 0:10, MATLAB automatically increments by 1. For example, try q = 0:10. 15 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 over the interval [−2, 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 2 a vector y containing the values of f (x) = xe−x 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 2 of the values in x. Since MATLAB functions are array smart, exp(-x.^2) contains the values of e−x for each of the entries of x. Finally, since .* is an array operation, x.*exp(-x.^2) contains the values 2 of f (x) = xe−x 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. 0.5 25 0.4 20 0.3 15 0.2 10 0.1 5 0 0 −0.1 −5 −10 −0.2 −15 −0.3 −20 −0.4 −0.5 −3 −25 −2 −1 0 1 2 3 −30 Figure 2.7. The graph for Example 4. 4 −20 −10 0 10 20 30 Figure 2.8. The parametric curve in Example 5. If several figure windows are open, the last one visited is the “current figure window.” 16 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 deﬁned by t → (t cos t, t sin t) for 0 ≤ t ≤ 8π . We start with the command t = linspace(0,8*pi,200), which produces 200 equally spaced points5 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,8*pi,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. 0.4 y y 0.2 s 20 0 t 15 −0.2 10 −0.4 5 −0.6 0 1 0.5 1 0 −0.5 y = sin t −0.8 0.5 0 −1 −0.5 −1 −1 x = cox t 0 Figure 2.9. The spiral curve with x = cos t, y = sin t, and z = t. 5 1 2 3 4 5 6 7 Figure 2.10. Plots of y and ys . Type help linspace for more information on using this command 17 8 9 10 Colors, markers, and line styles. Execute help plot at the MATLAB prompt and read the resulting help file. Pay particular attention to the various line styles, markers, and colors that can be used with MATLAB’s plot command. You can produce strikingly different plots by varying the choice of these three attributes. Try the command plot(t,y,'rx:'), shg, and examine its affect on your plot. This plot command has the third argument 'rx:'. The three symbols between the single quotes select, in order, a color, a marker, and a line style. Experiment with other combinations, such as plot(t,y,'s'), plot(t,y,'md'), and plot(t,y,'k--'). Use the shg command to view the results of each command. Multiple graphs in a figure. There are several ways of doing this in MATLAB. Example 6. The initial value problem y + 2y + 2y = cos 2t, with y(0) = −1 and y (0) = 2 has the solution y(t) = yt (t) + ys (t), where yt (t) = e −t 9 7 sin t − cos t , 10 10 and ys (t) = 1 1 sin 2t − cos 2t 5 10 are the transient response and the steady-state solution, respectively. Plot the graphs of y and ys over the interval [0, 3π ] on the same ﬁgure. Use a solid line for y and a dashed line for ys . Use a legend to label the graphs. We can use t = linspace(0,3*pi) to get 100 equally spaced t-values between 0 and 3π . The commands >> y_t = exp(-t).*((7/10)*sin(t) -(9/10)*cos(t)); >> y_s = (1/5)*sin(2*t) - (1/10)*cos(2*t); >> y = y_t + y_s; compute the steady-state solution, the transient response, and the total response. A naive first try at plotting y and ys together might be >> plot(t,y) >> plot(t,y_s,'--'), shg However, MATLAB erases the first plot when the second plot command is executed. The commands >> plot(t,y,t,y_s,'--') >> grid on >> legend('y','y_s') will produce an image similar to that in Figure 2.10, with the graphs of both y and ys on the same figure. Notice that the parameters of the plot command come in groups. The first group consists of t and y, which is the data for the first curve. The second group has three entries, t, y_s, and '--'. This is the data for the the second curve plus a designation of a line style. The command grid on does just what it says — it adds a grid to the figure. Type grid off if you want to remove the grid. The legend command 18 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. 19 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 window8 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 ﬁgure, 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) = Cet − 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 20

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement