Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Matlab M File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

4.

The Use of Function M-Files

In Chapter 2 we discussed script M-les, and how they can be used to facilitate the preparation of complicated graphics. Here we will introduce function M-les, which are very like script M-les, but can pass parameters and isolate variables. These two capabilities can be exploited to add new functions to MATLABs already extensive list, and to extend our ability to perform computational experiments and prepare graphics. In this chapter we will emphasize the use of MATLABs built-in editor. If you use a different editor, and one of the authors does, then ignore these parts. However, the MATLAB editor has several connections with MATLAB iself that make it a good choice. New Functions in MATLAB It is very easy to add your own functions to the long list provided by MATLAB. Lets start with a very easy example. Example 1. Create a function M-le for the function f (x) = x 2 1. Execute edit at the command line to open the MATLAB editor 1 and enter the following three lines (one of them is blank, and is provided for readability): function y = f(x) y = x^2-1; The rst line of a function M-le must conform to the indicated format. It is this rst line that distinguishes between a function M-le and a script M-le. The very rst word must be the word function. The rest of the rst line has the form dependent_variables = function_name(independent_variables) In the function f, y = f(x) indicates that x is the independent variable and y is the dependent variable. The rest of the function M-le denes the function using the same syntax we have been using at the MATLAB prompt. Remember to put a semicolon at the end of lines in which computations are done. Otherwise the results will be printed in the Command Window. When you save the le, you will be prompted to use the le name f.m. The le name should always be the same as the function name, followed by the sufx .m, so accept the suggestion. Thats all there is to it. Now if you want to compute f (3) = (3)2 1 = 8, simply enter f(3) at the MATLAB prompt. >> f(3) ans = 8
1

There are several ways to open the editor. Explore the Toolbar and the Edit menu. 48

Making Functions Array Smart. There is one important enhancement you will want to make to the M-le f.m. If you try to compute f on a matrix or a vector, you will nd that it is not array smart. >> x = 1:5 x = 1 2 3 4 >> f(x) ??? Error using ==> ^ Matrix must be square.

This error message refers to the fact that we tried to compute x^2 for a vector x. We forgot to use array exponentiation instead of ordinary exponentiation. To edit the function to make it array smart we simply add one period: function y = f(x) y = x.^2-1; Now the function can handle matrices. With the same vector x, we get >> f(x) ans = 0

15

24

Notice that if x is a matrix, then so is x.^2. On the other hand, 1 is a number, so the difference x.^2-1 is not dened in ordinary matrix arithmetic. However, MATLAB allows it, and in cases like this will subtract 1 from every element of the matrix. This is a very useful feature in MATLAB. Example 2. An object thrown in the air obeys the initial value problem dy d 2y = 9.8 , dt2 dt with y(0) = 0 and y (0) = 120.

When we solve this linear equation, we nd that y= 649 49 t+ 1 et , 5 5

where y is the height in meters of the object above ground level after t seconds. Estimate the height of the ball after 5 seconds. This is a perfect situation for a function M-le, particularly if you are interested in predicting the height of the ball at a number of additional times other than t = 5 seconds. Open a new M-le in the editor, enter function y = height(t) y = -(49/5)*t + (649/5)*(1 - exp(-t)); 49

and save it as height.m. This time we needed no additional periods to make the function array smart. It is now a simple matter to nd the height at t = 5 seconds. >> y = height(5) y = 79.9254 Hence, the height of the ball at t = 5 seconds is 79.9254 meters. Example 3. Plot the height of the object in Example 2 versus time and use your graph to estimate the maximum height of the object and the time it takes the object to return to ground level. Although we could operate strictly from the command line to obtain a plot, we will will use a script M-le to do the work for us. Open a new M-le, enter the commands close all t = linspace(0,15,200); y = height(t); plot(t,y) grid on xlabel('time in seconds') ylabel('height in meters') title('Solution of y'''' = -9.8 - y'', y(0) = 0, y''(0) = 120') and save it in a le named height_drv.m. Notice that, since the rst line does not begin with the word function, this is a script M-le, not a function M-le. The command close all will close all open gure windows. The purpose of this command is to prevent gure windows from accumulating as we execute versions of the script. However, you should be cautious about using it, since you may close gures you want to have open. Notice that we used the function height dened in Example 2 to calculate the y-values over the time interval [0, 15]. You can execute the script M-le by typing height_drv at the MATLAB prompt. However, you can also select DebugRun2 from the editor menu. This menu item has the accelerator key F5. This means that after you edit the le, you can both save it and execute it with F5. The routine of editing, followed by F5 can be a great time saver as you rene an M-le. Running your script M-le should produce an image similar to that shown in Figure 4.1. If your le contain errors, you might hear a beep or a click when you press the F5 button. An error message will be reported in the MATLAB command window, often as a link. Clicking this link will bring up the editor with the cursor on the line in the where the error occurs. By examining the graph, we see that the object reaches a maximum height between 90 and 100 meters after about two or three seconds of ight. It returns to ground level (height zero) after approximately thirteen or fourteen seconds. You can use the zoom tool located on the toolbar in the gure window to obtain better estimates. This menu item changes to Save and Run if you have made changes since the last time you saved the le. 50
2

Solution of y = 9.8 y, y(0) = 0, y(0) = 120 100 80

height in meters

60 40

20 0

20 0 5 time in seconds 10 15

Figure 4.1. Plotting the solution of y = 9.8 y , y(0) = 0, y (0) = 120. Function M-les, Computational Exercises and Graphics Some of you might wonder why we had to use both the function M-le height.m and the script Mle height_drv.m to produce Figure 4.1 in Example 2. It takes time to write les, and the accumulation of les clutters up the directory in which they are saved. Starting with version 6 of MATLAB there is a way around this problem. Subfunctions in MATLAB 6. The answer is to dene the function height as a subfunction with the le height_drv.m. However, subfunctions are not allowed in script M-les. Open MATLABs built-in editor, enter function ch4examp3 close all t = linspace(0,15,200); y = height(t); plot(t,y) grid on xlabel('time in seconds') ylabel('height in meters') title('Solution of y'''' = -9.8 - y'', y(0) = 0, y''(0) = 120') function y = height(t) y = -(49/5)*t + (649/5)*(1 - exp(-t)); and save it as ch4examp3.m. Use the F5 key to execute the le. This should produce a plot similar to that in Figure 4.1. Notice that the code in ch4examp3 is precisely the same as the code in the two les height.m and height_drv.m created in Examples 2 and 3. However, this is a single function M-le with height included as a subfunction. 51

Functions of functions MATLABs funfun directory. MATLAB has a large number of functions that act on functions. If you type >> help funfun at MATLABs prompt, you will see a list of MATLAB routines for nding zeros and extrema of functions, tools for numerical integration, and many others. There is a suite of routines for solving differential equations, which we will look at in Chapter 8. For help on any of these functions, say fzero, execute help fzero and learn how to nd the zeros of a function. Example 4. Use fzero to nd the time it takes the object in Example 2 to return to ground level. The help command indicates that X = FZERO(FUN,X0) tries to nd a zero of the function FUN near X0. Thus, fzero needs two inputs, the name of a function, and an approximate value of the zero. We will use the function height from Example 2, and from Figure 4.1 we estimate that height has a zero near t = 13. In all versions of MATLAB you can invoke fzero with the command >> t = fzero('height',13) t = 13.2449 Notice that the function name must be entered between single quotes. Starting with version 6 of MATLAB, the use of >> t = fzero(@height,13) t = 13.2449 is encouraged. The expression @height is a function handle for the function height. In either case, we nd that the object returns to ground level after about 13.2 seconds. This certainly agrees with that we see in Figure 4.1. Example 5. Find the maximum height reached by the object in Example 2. In the list provided by help funfun we nd that MATLAB doesnt provide a function for nding the maximum of a function. However, the routine fminbnd will nd a local minimum, and a local maximum of a function can be determined by nding a local minimum of the negative of the function. Using help fminbnd, we learn that nding the minimum of a function on a given interval requires the input of a function and the beginning and endpoints of the interval in which to nd the minimum. Consequently, we will apply fminbnd to the negative of height on the interval [0, 5]. One approach would be to write a new function M-le encoding the negative of (49/5)t +(649/5)(1et ). However, lets pursue an alternative. MATLAB provides a perfect solution for the situation when you need a function, but do not want to go to the trouble of writing a function M-le, called an inline function.3 We could create our inline
3

Type help inline to get a thorough explanation of the use of inline functions. 52

function for the negative of height as >> f = inline('(49/5)*t - (649/5)*(1 - exp(-t))','t') f = Inline function: f(t) = (49/5)*t - (649/5)*(1 - exp(-t)) However, since we have already created height, it is easier to use the inline function >> f = inline('-height(t)','t') f = Inline function: f(t) = -height(t) From Figure 4.1 we estimate that the maximum occurs between t = 0 and t = 5, so the command >> t = fminbnd(f,0,5) t = 2.5836 nds the time at which the maximum occurs. Notice that there are no single quotes around f in fminbnd(f,1,5), so inline functions are treated differently from function M-les as inputs. Alternatively, the syntax t = fminbnd(inline('-height(t)'),1,5) will do the job in a single command. The maximum height is now easily calculated by >> h = -f(t) h = 94.6806 or by h = height(t). Compare these results with Figure 4.1. Using function M-les to pass parameters. The ability of function M-les to have input variables can be used to advantage when producing graphics. We will present a simple example. Example 6. Write a function M-le that will plot the solution to the initial value problem y + y = 2t cos t with y(0) = y0

over the interval [0, 4]. Write the le with y0 as an input variable. The equation is linear, and we nd that the general solution is y(t) = t (cos t + sin t) sin t + Cet . At t = 0, we nd that y0 = y(0) = C. Thus the function M-le function ch4examp6(y0) t = linspace(0,4*pi); y = t.*(cos(t) + sin(t)) - sin(t) + y0*exp(-t); plot(t,y), shg 53

will produce the required graph when ch4examp6(y0) is executed at the command line. Of course, you will want to add formatting commands to your function M-le. The result is shown in Figure 4.2. The one tricky formatting command is the one that produces the title. The command title(['y'' + y = 2tcos(t) with y(0) = ', num2str(y0), '.'])

requires the concatenation of text strings, as explained in the section "Text Strings in MATLAB" in Chapter 2.

y + y = 2tcos(t) with y(0) = 11. 15 10

5 y(t) 0

5 10

15 0 2 4 6 t 8 10 12 14

Figure 4.2. The output of ch4examp6(11).

Functions of Several Variables MATLAB allows multiple input and output variables in function M-les. Example 7. Write a function M-le for the function dened by f (t, x) = x 2 t. We need to choose a name for this function, so lets use the mnemonic xsqmt (x squared minus t). Then the following M-le describes this function: function y = xsqmt(t,x) % This is Example 7 of Chapter 4. y=x.^2-t; The rst line of the le starts with the word function. After that comes y=xsqmt(t,x), meaning that y is the dependent variable, and both t and x are independent variables. Everything on a line in an M-le after a percentage sign (%) is ignored by MATLAB. This can be utilized to put comments in a le, as we have done in the function xsqmt. Comment lines are useful ways to document your M-les. It is amazing how quickly we forget why we did things the way we did. Comment lines immediately after the function statement can be read using the MATLAB help command. 54

For example, if xsqmt is dened as above, saved as xsqmt.m, then help xsqmt gives the following response. >> help xsqmt This is Example 7 of Chapter 4. You can evaluate the function at (t, x) = (2, 5) as follows. >> xsqmt(2,5) ans = 23 Naming and Organizing Files Once you learn how to write M-les, they tend to accumulate rapidly. It is a good idea to give them appropriate names and to organize them into a directory structure that will make them easy to nd. Of course you will choose a method that suits you. We will present some general considerations. As one starts to use les, it is typical to save them all to the same directory. That is ne if you only have a few. When the number gets large enough that you have trouble identifying them, it becomes necessary to create new directories, and it is a good idea to use the directory system to differentiate the les. For example, you might create a directory named manual in which you save all les related to this Manual. The method of creating directories or folders depends on your operating system. You can use the MATLAB command mkdir, but this is usually less convenient. Once you have more than one directory, you will need to know how to navigate through them. For one thing, MATLAB has a current directory in which it operates. This directory is displayed in the Current Directory popup menu on the toolbar of the command window. You can also discover the current directory by executing pwd. The popup menu lists all of the directories you have visited recently, making it easy to navigate among them. You can change to a directory not on the popup menu using the browse button, labeled with an ellipsis (. . . ). You can also use the command cd. The MATLAB path. After you have created a couple of directories, you will have to become familiar with the MATLAB path. Difculties will arise in one of two ways. The rst happens when you try to execute an M-le and get the error message >> phony ??? Undefined function or variable 'phony'. However, you are sure you created phony.m just yesterday, and it worked ne. The problem here is probably that phony.m is in a directory that is not on the MATLAB path. The second difculty that can arise is that you execute an M-le, and, while it works, it is not doing what you know it should. In this case you probably have two les named phony.m, in different directories, and MATLAB is nding the wrong one. 55

The MATLAB path is the list of directories that MATLAB searches when it is looking for an M-le, in the order that they are searched. You can nd the path using the pathtool,4 which can be accessed using the command pathtool or by choosing the menu item FileSet Path... . The rst directory on the path is always the current directory, so you can be sure you are executing the correct M-le if you nd out what directory it is in, and then change directories so that it is the current directory. It is also possible to add directories to the MATLAB path using the pathtool. Files that you use frequently should be in directories that are permanently on the path. If you nd that you have two les with the same name, say phony, you can nd out which one is higher on the path with the command which phony. MATLAB will respond with the complete address of the rst instance of phony.m on the MATLAB path. If the address is not the one you expect, you know that you have a name conict. You could delete the offending le (probably not a good idea), you could change the name of one of the les, or you could just change directories so that the directory containing the right version of phony.m is the current directory. Either of the commands ls or dir will display a list of the les in the current directory. You can display the contents of the M-le phony.m on the command window with the command type phony. This works very well with short les, but not too well with long ones. Naming Functions and Variables. All of us typically refer to functions with one letter names, such as f or g. However, many important and commonly used functions have longer names. Think of the trigonometric functions, the logarithm, and the hyperbolic functions as examples. It is a good idea to follow that practice when naming your MATLAB M-les. Giving your function M-les distinctive names helps to avoid name conicts and might help you remember their functionality at a later date. For example, in Example 3 the name ch4examp3 was carefully chosen to reect the fact that the le is related to Example 3 in Chapter 4 of this Manual. The name of a function M-le has the form function_name.m, where function_name is the name you choose to call the function. While this name can be almost anything, there are a few rules. The name must start with a letter (either upper case or lower case). The name must consist entirely of letters, numerals, and underscores ( ). No other symbols are allowed. In particular, no periods are allowed. The name can be arbitrarily long, but MATLAB will only remember the rst 31 characters. Do not use names already in use such as cos, plot, or dfield6. If you do, MATLAB will not complain, but you will eventually suffer from the name duplication problem described earlier. The variable names used in a function M-le must satisfy the same rules that apply to the names of M-les. Other than that they are arbitrary. As a result the le f.m of Example 1 could have been written as function stink = funn(skunk) stink = skunk.^2 - 1; Save this le as funn.m and with x = 1:5 execute
4

Or you can type path at the MATLAB prompt. 56

>> funn(x) ans = 0 3

15

24

Compare this to the output produced earlier with f(x) and note that there is no difference. It is important to realize that the variable names used in function M-les are local to these les; i.e., they are not recognized outside of the M-les themselves. See Exercises 12 and 13. In addition variables that have been dened at the command line are not available within function M-les. Script M-les, on the other hand, do not isolate variables. Exercises

Find the solution of each of the initial value problems in Exercises 14, then craft an inline function for the solution. After insuring that your inline function is array smart, use the inline function to (i) plot the solution of the initial value problem on the given interval, and (ii) evaluate the solution at the right endpoint of the given interval. 1. y = t/y, with y(0) = 4, on [0, 4]. 2. y = 2ty 2 , with y(0) = 1, on [0, 5]. 3. y + y = cos t, with y(0) = 1, on [0, 5 ]. 4. y + 2y = sin(2t), with y(0) = 1, on [0, 4 ]. Find the solution of each of the initial value problems in Exercises 58, then craft a function M-le for the solution. After insuring that your function M-le is array smart, use the function to (i) plot the solution of the initial value problem on the given interval, and (ii) evaluate the solution at the right endpoint of the given interval. 5. y = (1 t)y, with y(0) = 1, on [0, 4]. 6. y = y sin(2t), with y(0) = 1, on [0, 2 ]. 7. y = y/t + t, y(1) = 1, on [0, 3]. 8. y + t 2 y = 3, with y(0) = 2, on [0, 5]. Find the solution of the given initial value problem in Exercises 912, then craft a function M-le for the solution. After insuring that your function M-le is array smart, plot the solution on the given interval. Use MATLABs fminbnd function to nd the minimum value of the solution on the given interval and the time at which it occurs. Use the gure windows Insert Text and Insert Arrow tools to annotate your plot with these ndings.5 9. y + 2ty = et , with y(0) = 0, on [0, 2]. 10. y y/t = t sin t, with y( ) = , on [0, 2 ]. 11. y = 1 + 2y/t, with y(1) = 3/4, on [1, 4].
2

12. y + y = t 2 , with y(0) = 1, on [0, 2]. Find the solution of the given initial value problem in Exercises 1316, then craft a function M-le for the solution. After insuring that your function M-le is array smart, plot the solution on the given interval. Use MATLABs fminbnd function and the technique of Example 5 to nd the maximum value of the solution on the given interval and the time at which it occurs. Use the gure windows Insert Text and Insert Arrow tools to annotate your plot with these ndings. 13. ty y = t 2 cos(t), with y( ) = 0, on [0, 2 ]. 14. y = y cos(t), with y(0) = 1, on [0, 2 ]. 15. y = (1 + y) sin(t), with y( ) = 0, on [0, 2 ].
5

If the gure toolbar is not visible, select View Figure Toolbar from the gure menu.

57

16. y + t 2 y = 3, with y(0) = 1, on [0, 3]. 17. The differential equation y +y = cos(4t) has the general solution y = (1/17) cos(4t)+(4/17) sin(4t)+Cet . Craft a function M-le for this solution as follows.
function y = f(t,C) y = 1/17*cos(4*t) + 4/17*sin(4*t) + C*exp(-t);

Plot a family of solutions for the differential equation with the following script.
t = linspace(0,2*pi,500); y = []; for C = -20:5:20 y = [y;f(t,C)]; end plot(t,y)

Follow the lead of Exercise 17 to plot the given families of solutions in Exercises 1823. Use the indicated constants and extend your plot over the given time interval. 18. y = 2/(t 2 + C), C = 1, 2, 3, 4, 5, on [2, 2]. 19. y = (1/4)t 2 (1/8)t + 1/32 + Ce4t , C = 1, 2, 3, 4, 5, on [0, 2]. 20. 21. 22. 23. y y y y = Ctet , C = 3, 2, 1, 0, 1, 2, 3, on [2, 2]. = (t/2)(cos(t) + sin(t)) (1/2) sin(t) + Cet , C = 3, 2, 1, 0, 1, 2, 3, on [0, 10]. = 1 + cos(t) + (C + t/2) sin(t), C = 0, 1, 2, 3, 4, 5, on [0, 6 ]. = (1/10) sin(t) + (1/5) cos(t) + et (C sin(2t) (1/5) cos(2t)), C = 3, 2, 1, 0, 1, 2, 3, on [0, 2 ].
2

24. A tank initially contains 20 gallons of pure water. A salt solution containing 2 lb/gal ows into the tank at a rate of 3 gal/min. A drain is open at the bottom of the tank through which ows salt solution from the tank at a rate of 2 gal/min. Set up and solve an initial value problem modeling the amount of salt in the tank at time t minutes. Write an inline function for your solution and use it to nd the salt content in the tank at t = 30 minutes. 25. Tank A initially contains 40 gallons of a salt solution. Pure water is poured into tank A at a rate of 2 gal/min. A drain is opened at the bottom of tank A so that salt solution ows directly from tank A into tank B at 2 gal/min, keeping the volume of the salt solution in tank A constant over time. Tank B initially contains 100 gallons of pure water. A drain is opened at the bottom of tank B so that the volume of solution in tank B remains constant over time. If x and y represent the salt content in tanks A and B, respectively, show that dx x = dt 25 and dy x y = . dt 25 50

Given that x(0) = 20, solve the rst equation for x, substitute the result into the second equation, then show that y = 40et/50 40et/25 . Write a function M-le to evaluate y at time t. Following the technique used in Examples 3-5, use your function to (i) construct a plot of the salt content in tank B over the time interval [0, 100], and (ii) use fminbnd to nd the maximum salt content in tank B and the time at which this occurs. 26. An object thrown into the air is known to obey the initial value problem y = 9.8 0.05y , y(0) = 0, y (0) = 200,

where y is the height of the ball above ground (in meters) at t seconds. The solution of this initial value problem is y(t) = 196t + 7920(1 et/20 ).

58

Following the lead of Examples 2-5 in the text, plot this solution, then nd its maximum height and the time at which it occurs. Then nd the time it takes the object to return to the ground. Question: Does the time it takes the object to reach its maximum height equal the time it takes the object to return to ground level from this maximum height? In other words, does it take the object the same amount of time to go up as it takes the object to come down? 27. A simple RC-circuit with emf V (t) = 3 cos(t) is modeled by the initial value problem RCVC + VC = 3 cos(t), VC (0) = 0, where R is the resistance, C the capacitance, is the driving frequency, and VC is the voltage response across the capacitor. Show that the solution is VC (t) = RC sin t + cos t et/(RC) . 1 + R 2 C 2 2

Create a function M-le for this solution as follows.


function V = f(t,R,C,w) V = (R*C*w*sin(w*t) + cos(w*t) - exp(-t/(R*C)))/(1 + R^2*C^2*w^2);

Now, call this function with the following script.


R = 1.2; C = 1; w = 1; t = linspace(0,2*pi,1000); V = f(t,R,C,w); plot(t,V)

Run this script for = 1, 2, 4, and 8, keeping R = 1.2 ohms and C = 1 farad constant. What happens to the amplitude of the voltage response across the capacitor as the frequency of the emf is increased? Why do you think this circuit is called a low pass lter? 28. Write a function M-le to calculate f (z) = |z|. Use it to graph f over the interval (3, 2). 29. Write a function M-le to compute the function f (t) = t 1/3 . Use it to graph the function over the interval [1, 1]. (This is not as easy as it looks. Read the section on complex arithmetic in Chapter 1.) 30. Write a function M-le to calculate the function f (t) = et (t 2 + 4et 5). a) Use the M-le to graph f over the interval (2.5, 3). b) Find all of the zeros in the interval (2.5, 3) of the function f dened in the previous exercise. 31. For the function funn dened in this chapter nd all solutions to the equation funn(x) = 5 in the interval [5, 5]. 32. Write an array smart function M-le to compute f (t) = 5. Remark: You will nd this exercise more difcult than it looks. There are a variety of tricks that will work, but the methods that are most consistent with the ways used for non constant functions (and therefore are most useful in programming applications) use the MATLAB commands size and ones. Use help on these commands. 33. Variables dened in functions are local to the function. To get a feel for what this means, create the function M-le
function y = fcn(x) A = 2; y = A^x;

Save the le as fcn.m. In MATLABs command window, enter the following commands.
A = 3; x = 5; y = fcn(x) A^x

59

Explain the discrepancy between the last two outputs. What is the current value of A in MATLABs workspace? 34. You can make variables global, allowing functions access to the variables in MATLABs workspace. To get a feel for what this means, create the function M-le
function y = gcn(x) global A A = 2; y = A^x;

Save the le as gcn.m. In MATLABs command window, enter the following commands.
global A A = 3; x = 5; y = gcn(x) A^x

Why are these last two outputs identical? What is the current value of A in MATLABs workspace?

60

You might also like