Matlab lesson 2

Matlab lesson 2 - Lesson 2 Using Matlab like a Graphing...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lesson 2: Using Matlab like a Graphing Calculator MATLAB is a high level programming language specifically designed for scientific computation. The advantages of using MATLAB over lower level programming languages is that it can be used effectively without having a deep understanding of the inner workings of the computer and it is relatively easy to do sophisticated graphics. The easiest way to learn how to use a piece of software is to use it! In these lessons, please do type in everything as instructed, but don’t feel limited by what is in the lesson. If you find yourself wondering what MATLAB might do if you typed in such-and-such, find out by typing it in! Goals of this lesson: In this lesson you will learn how to • • • • • • • use MATLAB interactively to perform calculations as you would on a scientific calculator; create variables in the workspace that can be scalars, vectors, or matrices; create patterned vectors and matrices; access and change entries in a vector or matrix; perform the usual arithmetic operations with matrices; perform element-wise operations with matrices; and sketch the graph of a function. Using MATLAB as a Scientfic Calculator When you first open MATLAB, the Command Window appears. In this window you can give commands to MATLAB. The commands are typed at the prompt >> and are executed by MATLAB when you type return. For instance, if you want MATLAB to calculate the value of 0.43−1.5 you can type >> 0.43^(-1.5) followed by the return key, just as you would on a calculator. MATLAB responds with ans = 3.5465 In these lessons, whatever appears after the prompt >> you should type (DO IT!). This should always be followed by the return key. After showing you what to type, we display the output that is produced by MATLAB and that you should see in the command window. For instance, here is how you can use MATLAB to calculate 5.65(4.3 + 7 − 2)/5.4: >> 5.64*(4.3 + 7 - 2)/5.4 ans = 9.7306 The number π can be accessed in MATLAB by typing pi and the number e is accessed by typing exp(1): >> pi ans = 3.1416 >> exp(1) ans = 2.7183 All the standard functions on a calculator are accessed in a predictable way in MATLAB. Here is a list of functions that are commonly used in calculus and their MATLAB equivalents. 1 2 When you use these functions, the input should be enclosed in round brackets. Here are some examples. >> sin(pi/7) ans = 0.4339 >> log10(0.001) ans = -3 >> log(exp(-10.3)) ans = -10.3000 >> exp(sqrt(9) - 3) ans = 1 You will find that you often want to repeat a command or slightly modify a command. To save you typing the command out again, you can use the up and down arrow keys to access previous commands and the right and left arrow keys to edit them. For instance, if you type the up arrow key, then the last command that you entered will appear at the prompt: >> exp(sqrt(9) - 3) Instead of typing return, type the up arrow key again. This time the command prior to that one appears: >> log(exp(-10.3)) Now, let’s edit this command. Using the left arrow key, move the cursor so that it is between the g of log and the parenthesis, (. (You can also click there with the mouse if you prefer.) Delete the word log and replace it with sin and then type return. >> sin(exp(-10.3)) ans = 3.3633e-05 Variables, Equals Sign as Assignment, and Suppressing Output Notice that when MATLAB performs a calculation it stores the result in a variable called ans. This is a variable in the workspace that can be accessed and used in the next calculation. You probably have a button on your calculator that accesses the result of the previous calculation; typing ans has the same effect in MATLAB. For instance, the following code calculates the value of 1/(5 sin(π /7)) in three steps: Name Math notation Matlab sine sin sin cosine cos cos tangent tan tan cosecant csc csc secant sec sec cotangent cot cot log base e ln log log base 10 log10 log10 log base 2 log2 log2 exponential exp √ square root sqrt absolute value || abs 3 >> sin(pi/7) ans = 0.4339 >> 5*ans ans = 2.1694 >> 1/ans ans = 0.4610 You can also create your own variables. For instance, when you type >> x = 4 x= 4 MATLAB creates a variable in the workspace called x and stores the value 4 in this variable. A ‘variable’ for MATLAB is really a location in memory. In other words, MATLAB has located a block of memory that it refers to as x. Whenever x is typed now in the workspace, MATLAB will look in that location and read off the value that is stored there. Right now, the value is 4, so if we type >> x^2 + x ans = 20 MATLAB calculates the value of x2 + x = 42 +4. We can easily change the value of x. For instance, suppose we want x to have the value −3. We can do this by simply typing: >> x = -3 x= -3 Now when we calculate x2 + x we are calculating the value of (−3)2 + (−3): >> x^2 + x ans = 6 Variables in MATLAB are case-sensitive. In other words, x and X are different. Since we haven’t introduced a variable X in this lesson MATLAB complains when we ask it to do a calculation using X: >> X^2 + X ??? Undefined function or variable ’X’. It can’t perform the calculation because it doesn’t know what X is. When we use an equals sign in ordinary mathematics it can mean different things depending on the context. For instance, when we write the equals sign indicates that we want to find all those values of x that make the value of the expression on the left the same as the value of the expression on the right. In this case, these values are -3 and 2. On the other hand, when we write the equals sign here indicates that, whatever the value of x, the value of the expression on the left is the same as the value of the expression on the right. In general, computers aren’t very good at dealing with ambiguity and in MATLAB an equals sign can only be used in a very specific way and it has a very specific meaning. In particular it is an assignment command; whenever you (x + 3)(x − 2) = x2 + x − 6, (x + 3)(x − 2) = 0, 4 type an equals sign, it should be preceded, on the left, by the name of a variable and it should be followed, on the right, by an expression that can be evaluated. MATLAB responds by evaluating the expression on the right and storing the result in the variable on the left. (If the variable on the left doesn’t already exist in the workspace then it creates it, if it does already exist in the workspace then its old value is lost and is replaced with the value of the expression.) This meaning of the equals sign allows us to type some expressions that look very weird on paper. For instance, consider what happens when we type x = x + 3 in the Command Window. On paper, this is nonsense. To MATLAB however, it makes perfect sense. It calculates the expression on the right and gets x + 3 = −3 + 3 = 0 (since the value of x in this lesson is presently −3) and stores this number in the variable x. So now x has the value 0: >> x = x + 3 x= 0 When we use a variable to calculate a quantity and then store the value obtained back in that same variable, we will say that we have ‘overwritten’ the old value with the new value. Thus, in the example above, we overwrote x with x + 3. You will see that it is very common to do this in scientific computing. If we type a semicolon after a command but before typing return, MATLAB will execute the command but will suppress the output. In other words, it won’t print the output to the screen. For example, type: >> y = 2*x + 5; >> It looks like MATLAB hasn’t done anything, but in fact it has. It calculated the quantity 2x + 5 = 2(0) + 5 = 5 and stored the result in a variable called y . Thus, if you ask MATLAB what the value of y is or tell it to perform a calculation with y it doesn’t complain the way it did with X above: >> y y= 5 >> y^2 - 10 ans = 15 Although right now it may seem strange to suppress the output (why would you want MATLAB to calculate something if you didn’t want to see the result?), you will see shortly that it is very useful to be able to do this. You will often have MATLAB perform hundreds or thousands of calculations, and you wouldn’t want to see hundreds or thousands of numbers being printed out to the screen. When we create variables in calculus, we often give them suggestive names. For instance, we might call the radius of a circle r, or the distance travelled d. Similarly, when you create variables in MATLAB you will want to give them suggestive names. A name doesn’t have to be a single letter only. It can actually be a name. For instance, if a variable represents the radius of a circle you might call it radius. However, it’s a good idea to avoid using names that are English names. This is because many English names already have a meaning in MATLAB. For instance, if a variable represented a length you might be tempted to call it length. However, this is a bad idea, since length is a MATLAB command (see below) that calculates the length of a vector. So, it’s a good idea to misspell or abbreviate names when creating variables. For instance, you might call the variable len instead. 5 Creating Variables that are Matrices The basic variable in MATLAB is a matrix rather than a number. For instance, the variable x that we introduced above is considered by MATLAB to be a 1 × 1 matrix. Higher dimensional matrices can be constructed in MATLAB in several ways. The simplest way is to type in the entries one by one; square brackets surround all of the entries, the entries in each row are separated either by a space or by a comma, and the rows are separated by a semi-colon. For instance, to create the variables ￿ ￿ ￿￿ 01 ￿ ￿ 2 −1 0 4 4 3 , A= B = 1 3 0 −1 , C= , and D= 132 −1 −2 0 we can type: >> A = [0 1; 4 3; -2 0] A= 01 43 −2 0 >> B = [1 3 0 -1] B= 1 3 0−1 >> C = [2, -1, 0; 1, 3, 2] C= 2 −1 0 132 >> D = [4; -1] D= 4 −1 Creating Patterned Vectors and Matrices As you will see when we discuss how to graph a function using MATLAB, we often want to create vectors that are very long (it would not be unusual to have vectors that have hundreds or thousands of entries) and whose entries start at one number and increase incrementally until they reach another number. You wouldn’t want to have to type out all these numbers, so MATLAB has a way of creating such vectors; if you type a:b (where a and b are numbers) MATLAB interprets this to be the row vector whose first entry is a and whose entries increase by 1 unit until they get to b. Here are some examples: >> 0:5 ans = 012345 >> -2.3:0.7 ans = −2.3000 −1.3000 −0.3000 0.7000 >> 4.1:6.7 ans = 4.1000 5.1000 6.1000 If you want a different step size then you can type a:c:b. This is a row vector whose first entry is a and whose entries increase by c units until they get to b, as illustrated in the following example: >> 0:.2:1.5 ans = 6 0 0.2000 0.4000 0.6000 0.8000 1.0000 1.2000 1.4000 The commands ones and zeros produce a matrix whose entries are all 1’s or all 0’s respectively. When you use the command you indicate how many rows and columns the matrix should have as shown in the examples below. >> ones(2, 3) ans = 111 111 >> zeros(2, 1) ans = 0 0 The command eye produces an identity matrix. Since identity matrices are always square, you only have to specify the number of rows you want the matrix to have as shown in the example below. >> eye(3) ans = 100 010 001 When you create a large matrix (for instance when you create a vector using the colon notation) it can be difficult to work out exactly how many entries it has. You can do this with the size command (or length command in the case of a vector). The size command tells you the number of rows and columns that a matrix has, the length command tells you how many entries a vector has. Here are some examples using these. >> size(A) ans = 32 >> ones(size(A)) ans = 11 11 11 >> length(B) ans = 4 >> length(3.2:.01:5.6) ans = 241 If x is a vector then sum(x) is the sum of all its entries. If x is a matrix, then sum(x) is a row vector consisting of the sum of the entries in each column. Here are some examples: >> sum(B) ans = 3 >> sum(A) ans = 2 4 7 Accessing and Changing Entries in a Matrix If M is a matrix variable in MATLAB then M(1, 2) refers to the entry in the first row and second column, in other words it’s M12 . Similarly, M(3, 1) refers to the entry M31 etc. To illustrate, consider the matrices A, B and D that you have in your workspace. They should be: ￿￿ 01 ￿ ￿ 4 A = 4 3 , B = 1 3 0 −1 , D= −1 −2 0 >> A(3, 1) ans = -2 >> B(2, 1) ??? Index exceeds matrix dimensions. Notice that, since B has only one row, there is no element B21 , so MATLAB complained when we tried to ascertain its value. Notice also that there is no zero’th row or column, as illustrated in the following example. A(0,1) ??? Subscript indices must either be real positive integers or logicals. If M is a row vector then you don’t need to specify which row the entry is in, since it must be in the one and only row. In other words you can use M(2) as a short-hand for M(1, 2). Similarly, if M is a column vector, M(3) means the same thing as M(3, 1). Here are two examples: >> B(3) ans = 0 >> D(1) ans = 4 We can easily change an individual entry in a matrix by assigning it a new value. In the first example below, we change A11 so that it has the value 7, in the second example, we change A21 so that it is the square of its previous value. >> A(1, 1) = 7 A= 71 43 −2 0 >> A(2, 1) = A(2, 1)^2 A= 71 16 3 −2 0 We can access a whole row or column of a matrix M by using a colon. For instance M(1, :) is the row vector consisting of all those entries that lie in the first row and in any column of M . In other words, it is the first row of M . Similarly, M(:, 2) is the column vector consisting of all those entries that lie in any row and in the second column of M . In other words, it is the second column of M . Here are two examples: >> A(3, :) ans = −2 0 >> A(:, 1) 8 ans = 7 4 −2 In the examples below we use this notation to change a whole row or column of a matrix. In the first example we return the matrix A to its original value by reconstructing its first column. In the second example we try to change the first row of A so that it is equal to the first column of A. However, since the length of the row is different from the length of the column, MATLAB complains. >> A(:,1) = [0; 4; -2] A= 01 43 −2 0 >> A(1,:) = A(:,1) ??? Subscripted assignment dimension mismatch. You can also add a whole row or column to a matrix. However, the row or column you are adding has to be the correct size so that the result is still a matrix. In the next example we extend D making it into the 3 × 2 matrix 42 −1 2 22 Notice, however, that the first way we try to do this it complains because the result would not be a matrix. >> D(:, 2) = 2*ones(3, 1) ??? Subscripted assignment dimension mismatch. >> D(:, 2) = 2*ones(2, 1) D= 42 −1 2 >> D(3, :) = 2*ones(1, 2) D= 42 −1 2 22 Performing Arithmetic Operations with Matries MATLAB interprets the operations +, -, * and ^ to mean matrix arithmetic. To illustrate, consider the matrices A and C that you have in the workspace. Their values should be: ￿ ￿ 01 2 −1 0 4 3 A= and C= . 132 −2 0 For instance, since A is 3 × 2 and C is 2 × 3, AC is defined and is a 3 × 3 matrix. We can get MATLAB to find its value by typing: >> A*C ans = 1 32 11 5 6 −4 2 0 9 On the other hand, since A and C have different sizes, A + C is not defined and MATLAB complains when we try to evaluate it: >> A + C ??? Error using ==> plus Matrix dimensions must agree. Similarly, A2 means A multiplied by itself, which is not defined, since you can’t multiply a 3 × 2 matrix by a 3 × 2 matrix. We see that MATLAB complains when we try to evaluate it: >> A^2 ??? Error using ==> mpower Matrix must be square. There is an exception to this. On paper, the expression A + 5 is undefined because you can’t add a 3 × 2 matrix to a 1 × 1 matrix (or scalar). However, MATLAB allows you to add a scalar to a matrix. It interprets the sum to be the matrix that is obtained when the scalar is added to each entry in the matrix: >> A + 5 ans = 56 98 35 An apostrophe is used to indicate the transpose of a matrix: >> A’ - C ans = −2 5 −2 0 0 −2 Performing Operations on Each Entry in a Matrix Individually Although it’s wonderful how easy it is to do matrix arithmetic in MATLAB, you will often find that you don’t want to do matrix arithmetic, but instead want to perform some kind of arithmetic operation to the individual entries of a matrix or vector. As a general rule, if you precede an operation with a period, then that tells MATLAB to perform that operation on each entry of the matrix individually rather than to perform matrix arithmetic. The examples in this section illustrate this. They use the matrices A, C and D in the workspace whose values are: ￿ ￿ 01 42 2 −1 0 A = 4 3 , C= , and D = −1 2 . 132 −2 0 22 The expression A*D means the matrix product of A and D. This is undefined since the number of columns of A is not equal to the number of rows of D. However, if we precede the * with a period and type A.*D then each entry in A is multiplied by the corresponding entry in D as shown below: >> A*D ??? Error using ==> mtimes Inner matrix dimensions must agree. >> A.*D ans = 02 −4 6 −4 0 The operation .∗ is only defined if the dimensions of the two matrices are the same: >> C*A 10 ans = −4 −1 8 10 >> C.*A ??? Error using ==> times Matrix dimensions must agree. Similarly, ./ means divide corresponding entries and .^n means raise each entry to the power of n. The following examples illustrate this. Notice that when we try to divide by zero MATLAB returns Inf as the answer, but alerts us with a warning that we may be doing something we weren’t expecting to do. >> A./D ans = 0 0.5000 −4.0000 1.5000 −1.0000 0 >> A./C’ Warning: divide by zero. ans = 0 1 −4 1 −Inf 0 >> A.^2 ans = 01 16 9 40 You will never need to type .+ or .- since the matrix interpretation of + and - already is to add (respectively subtract) corresonding entries. As a general rule, MATLAB functions such as sin or exp will accept a vector and not just a number as their input. When the input is a vector, MATLAB evaluates the function at each entry in the vector and returns this whole vector of values. As you will see in the next section, this is very useful for sketching graphs of functions. >> x = 0:(pi/6):pi x= 0 0.5236 1.0472 1.5708 2.0944 2.6180 3.1416 >> sin(x) ans = 0 0.5000 0.8660 1.0000 0.8660 0.5000 0.0000 Sketching the Graph of a Function MATLAB sketches functions the way you learnt to do so many years ago: by plotting points. To illustrate this, let’s consider the function f (x) = x2 x . +1 If you were to plot this function by plotting points you would start by setting up a table similar to the one below. 11 x y -2 -0.4 -1 -0.5 0 0 1 0.5 2 0.4 You would then plot these points and connect the dots. To do this in MATLAB we first create a vector with all of the x-coordinates. You can call this vector whatever you want. We’ll call it x since that seems like a reasonable choice in the context. >> x = -2:2 x= −2 −1 0 1 2 Now we need to create the vector that has all of the corresponding y coordinates. Let’s do this one step at a time. First notice that >> x.^2 ans = 41014 is a vector consisting of each coordinate squared. This means that >> x.^2 + 1 ans = 52125 is a vector consisting of each coordinate squared plus one. To get the vector of y -values, we need to take each value in x and divide by its corresponding value in the vector above. In other words we need to dot-divide each entry in x by each entry in the vector above. Thus >> y = x./(x.^2 + 1) y= −0.4000 −0.5000 0 0.5000 0.4000 is the vector of y -values. Notice that this looks like the formula for the function where all of the operations have a dot preceding them. We can then use the plot command to plot the points: >> plot(x, y) 0.5 0.4 0.3 0.2 0.1 0 −0.1 −0.2 −0.3 −0.4 −0.5 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 Look for the plot on your screen; it will be in a different window. It’s not a very detailed plot of the function and it looks a little funny because we only used a few points. To get a better plot we should use more points that cover a wider range and are closer together: >> x = -5:.1:5; >> y = x./(x.^2 + 1); >> plot(x, y) 12 0.5 0.4 0.3 0.2 0.1 0 −0.1 −0.2 −0.3 −0.4 −0.5 −5 −4 −3 −2 −1 0 1 2 3 4 5 Notice that we used the semicolon to suppress the output when creating the vectors x and y ; there was no reason for us to see all of those numbers. The hardest part of plotting a graph on a computer or calculator is deciding what x-values to use in your plot. There are basically two issues; what range of x values should be used, and how large the spaces should be between the x-values. There is no easy answer to either question. Calculators often use −10 ≤ x ≤ 10 as a default range. This may be a good place to start if you don’t otherwise have any idea of what range to use. To determine the spaces between the x-values, remember that the smaller the spaces are, the more realistic the graph will look. A good rule of thumb is to choose the spacing depending on the range, so that there are about 500 points being plotted. In the example below, we sketch the graph of g (x) = sin(π /x). Recall that this graph oscillates infinitely often as x approaches 0. Notice that near 0 we use more points because we want to see these oscillations on the graph, (we’ll never see all of them though; we’d have to use infinitely many points for that!), and we don’t attempt to sketch the graph too near to x = 0. >> x1 = -3:.1:-1; >> x2 = -1:.001:-.1; >> x3 = .1:.001:1; >> x4 = 1:.1:3; >> x = [x1, x2, x3, x4]; >> y = sin(1./x); >> plot(x, y) 1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 −1 −3 −2 −1 0 1 2 3 Notice that the graph should be oscillating between -1 and +1 but sometimes it seems to turn around before -1 or before +1. This is because, the x-value where it achieves the −1 or the +1 13 is not included in the x-values being plotted. So, the graph as shown is misleading and doesn’t accurately depict the complete graph of the function. Notice that, when you plot a function using Matlab, it connects the dots. This means that a jump discontinuity in a function will look like a vertical line (or a nearly vertical line, depending on how much space there is between x values in your plot) and if a function has a vertical asymptote, then Matlab will connect the pieces on either side of the asymptote. For instance, consider the function ￿ |x − 3| −1 x < 3 h(x) = = 1 x>3 x−3 The graph of this function consists of two horizontal half-lines: ✻ 1 ✲ −10 0 −1 3 10 However, when we sketch it in Matlab, these two lines are connected by a nearly vertical line: >> x = -10.01:.1:10.01; >> y = abs(x - 3)./(x - 3); >> plot(x, y) 1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 −1 −15 −10 −5 0 5 10 Notice the function h isn’t defined at x = 3, so to avoid having 3 as one of the entries in our x vector, we started the vector at −10.01 instead of at −10. If you did have 3 as one of the entries in your vector it wouldn’t be a big deal though; MATLAB would simply give you a warning message saying that it was being asked to divide by 0 when calculating y and omit that point when it does the plot. Indeed, in this case the plot looks the way it ought to, since MATLAB doesn’t connect the two horizontal lines! Every time you create a new plot, the old plot is lost. If you want to keep the old plot and put the new plot in a new window, type figure before creating the new plot. This opens up a new figure window and makes it active. When you then create a new plot, it will appear in this window. Alternatively, if you want the new plot to appear in the same window as the old plot without losing the old plot, type hold on. This tells Matlab to superimpose the new plot on the old plot. In the 14 following example, we plot the graph of y = x2 along with its tangent line at x = 1. Notice that y = 2x − 1 is the equation of this tangent line. >> x = -1:.01:3; >> y = x.^2; >> plot(x, y) >> ytan = 2*x - 1; >> hold on >> plot(x, ytan) 10 8 6 4 2 0 −2 −4 −1 −0.5 0 0.5 1 1.5 2 2.5 3 When you use hold on the new plot does not have to use the same x values as the old plot. If new x-values are used, Matlab will adjust the window to accommodate the new values. In the next example, we use hold on to plot a graph of the piecewise function ￿ 4/(x − 2) x ≤ 1 k (x) = x2 x>1 The first command hold off undoes the hold on command. The effect is that the first plot is created in the active plot window, erasing what was previously there. >> hold off >> x = -3:.01:1; >> y = 4./(x - 2); >> plot(x, y) >> hold on >> x = 1:.01:2.5; >> y = x.^2; >> plot(x, y) 8 6 4 2 0 −2 −4 −3 −2 −1 0 1 2 3 15 Miscellany You may type more than one command on one line. The commands should be separated by either commas or semicolons. Any command that ends with a semicolon will have its output suppressed. >> x = 2, y = cos(.3), z = 3*x*y x= 2 y= 0.9553 z= 5.7320 >> x = 5; y = cos(.5); z = x*y^2 z= 3.8508 Although MATLAB performs calculations to a very high precision, by default it only prints out 4 decimal places to the screen. If you want to see the results to a higher degree of precision you can type >> format long To return to 4 decimal places, you can type >> format short MATLAB generally leaves a blank line between the commands you type and its response. If you want to omit this line, you can type >> format compact To reinstate the blank lines, type >> format loose MATLB provides online help. One way to get help is to click on the Help menu in the command window. If you know the name of the command you want to use, but are having trouble remembering exactly how to use it or exactly what it does, you can type help followed by the name of the command. When working with MATLAB you will see that you create many variables and may not be able to keep track of all of them. To see what variables you have created in the workspace type >> who Your variables are: ans x y For more information about these variables you can type >> whos Name Size Bytes Class ans 1x1 8 double array x 1x1 8 double array y 1x1 8 double array Grand total is 2 elements using 16 bytes If you want to clear one or more of these variables from the workspace, you can use the clear command. If you type clear followed by the name of the variable(s) you would like to remove then MATLAB will remove only those variables. If you type clear followed by nothing, then MATLAB will clear all of the variables from the workspace. >> clear x >> who Your variables are: 16 ans y >> clear >> who MATLAB doesn’t appear to respond because there are no variables in the workspace to report. ...
View Full Document

Ask a homework question - tutors are online