Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recap Function M-files Syntax of Function M-Files Comments Multiple Input and Output Functions.

Similar presentations


Presentation on theme: "Recap Function M-files Syntax of Function M-Files Comments Multiple Input and Output Functions."— Presentation transcript:

1

2 Recap Function M-files Syntax of Function M-Files Comments Multiple Input and Output Functions

3 Functions with No Input or No Output Although most functions need at least one input and return at least one output value, in some situations no inputs or outputs are required For example: consider this function, which draws a star in polar coordinates: function [] = star( ) theta = pi/2:0.8*pi:4.8*pi; r = ones(1,6); polar(theta,r) The square brackets on the first line indicate that the output of the function is an empty matrix (i.e., no value is returned) The empty parentheses tell us that no input is expected If, from the command window, you type star then no values are returned, but a figure window opens showing a star drawn in polar coordinates

4

5 Continued…. There are numerous built-in MATLAB functions that do not require any input. For example: A = clock returns the current time: A = 1.0e+003 * Columns 1 through 4 2.0050 0.0030 0.0200 0.0150 Columns 5 through 6 0.0250 0.0277 Also, A = pi returns the value of the mathematical constant p: A =3.1416 However, if we try to set the MATLAB function tic equal to a variable name, an error statement is generated, because tic does not return an output value: A = tic ???Error using ==> tic Too many output arguments The tic function starts a timer going for later use in the toc function

6 Determining the Number of Input and Output Arguments There may be times when you want to know the number of input arguments or output values associated with a function MATLAB provides two built-in functions for this purpose The nargin function determines the number of input arguments in either a user-defined function or a built-in function The name of the function must be specified as a string, as, for example: in nargin('sin') ans =1 The remainder function, rem, requires two inputs; thus, nargin('rem') ans =2

7 Continued…. When nargin is used inside a user-defined function, it determines how many input arguments were actually entered This allows a function to have a variable number of inputs Recall graphing functions such as surf When surf has a single matrix input, a graph is created, using the matrix index numbers as the x – and y - coordinates. When there are three inputs, x, y, and z, the graph is based on the specified x- and y –values The nargin function allows the programmer to determine how to create the plot, based on the number of inputs

8 Continued…. The surf function is an example of a function with a variable number of inputs If we use nargin from the command window to determine the number of declared inputs, there isn’t one correct answer The nargin function returns a negative number to let us know that a variable number of inputs are possible: nargin('surf') ans = -1 The nargout function is similar to nargin, but it determines the number of outputs from a function: nargout('sin') ans = 1 The number of outputs is determined by how many matrices are returned, not how many values are in the matrix We know that size returns the number of rows and columnsin a matrix, so we might expect nargout to return 2 when applied to size. However, nargout('size') ans =1 returns only one matrix, which has just two elements, as for example, in x = 1:10; size(x) ans = 1 10

9 Continued…. An example of a function with multiple outputs is max : nargout('max') ans =2 When used inside a user-defined function, nargout determines how many outputs have been requested by the user Consider this example, in which we have rewritten the function to create a star: function A = star1( ) theta = pi/2:0.8*pi:4.8*pi; r = ones(1,6); polar(theta,r) if nargout==1 A = 'Twinkle twinkle little star'; end If we use nargout from the command window, as in nargout('star1') ans = 1 MATLAB tells us that one output is specified. If we call the function simply as star1 nothing is returned to the command window, although the plot is drawn If we callthe function by setting it equal to a variable, as in x = star1 x = Twinkle twinkle little star a value for x is returned, based on the if statement embedded in the function, which used nargout to determine the number of output values

10 Local Variables The variables used in function M-fi les are known as local variables The only way a function can communicate with the workspace is through input arguments and the output it returns Any variables defined within the function exist only for the function to use For example: consider the g function previously described: function output = g(x,y) % This function multiplies x and y together % x and y must be the same size matrices a = x.*y; output = a; The variables a, x, y, and output are local variables They can be used for additional calculations inside the g function, but they are not stored in the workspace To confi rm this, clear the workspace and the command window and then call the g function: clear, clc g(10,20) The function returns g(10,20) ans = 200

11 Continued…. Just as calculations performed in the command window or from a script M-fi le cannot access variables defined in functions, functions cannot access the variables defined in the workspace This means that functions must be completely self-contained: The only way they can get information from your program is through the input arguments, and the only way they can deliver information is through the function output Consider a function written to find the distance an object falls due to gravity: function result = distance(t) %This function calculates the distance a falling object %travels due to gravity g = 9.8 %meters per second squared result = 1/2*g*t.^2;

12 Continued…. The value of g must be included inside the function It doesn’t matter whether g has or has not been used in the main program How g is defined is hidden to the distance function unless g is specified inside the function Of course, you could also pass the value of g to the function as an input argument: function result = distance(g,t) %This function calculates the distance a falling object %travels due to gravity result = 1/2*g*t.^2;

13 Global Variables Unlike local variables, global variables are available to all parts of a computer program In general, it is a bad idea to define global variables However, MATLAB protects users from unintentionally using a global variable by requiring that it be identified both in the command-window environment and in the function that will use it Consider the distance function once again: function result = distance(t) %This function calculates the distance a falling object %travels due to gravity global G result = 1/2*G*t.^2; The global command alerts the function to look in the workspace for the value of G. G must also have been defined in the command window as a global variable: global G G = 9.8; This approach allows you to change the value of G without needing to redefine the distance function or providing the value of G as an input argument to the distance function

14 Creating ToolBox of Functions When a function is called in MATLAB, the program first looks in the current folder to see if the function is defined If it can’t find the function listed there, it starts down a predefined search path, looking for a fi le with the function name To view the path the program takes as it looks for files, select File -> Set Path from the menu bar or type pathtool in the command window

15

16 Continued…. As more and more functions are created to use in programming, it may be needed to modify the path to look in a directory where personal tools have been stored. For example: suppose you have stored the degrees-to- radians and radians-to-degrees functions created in a directory called My_functions. You can add this directory to the path by selecting Add Folder from the list of option buttons in the Set Path dialog window. You’ll be prompted to either supply the folder location or browse to find it (shown in next slide)

17

18 Continued…. MATLAB now first looks into the current folder for function definitions and then works down the modified search path

19 Continued…. Once a folder is added to the path, the change applies only to the current MATLAB session, unless changes are saved permanently Clearly, permanent changes should never make to a public computer However, if someone else has made changes you wish to reverse, you can select the default button to return the search path to its original settings The path tool allows to change the MATLAB search path interactively; however, the addpath function allows to insert the logic to add a search path to any MATLAB program Consult help addpath if you wish to modify the path in this way. MATLAB provides access to numerous toolboxes developed at The MathWorks or by the user community

20 Anonymous Functions and Function Handles Normally, if there is trouble of creating a function, you will want to store it for use in other programming projects However, MATLAB includes a simpler kind of function, called an anonymous function Anonymous functions are defined in the command window or in a script M- file and are available—much as are variable names—only until the workspace is cleared To create an anonymous function, consider the following example: ln = @(x) log(x) The @ symbol alerts MATLAB® that ln is a function. Immediately following the @ symbol, the input to the function is listed in parentheses. Finally, the function is defined. The function name appears in the variable window, listed as a function_handle:

21 Continued…. Anonymous functions can be used like any other function—for example, ln(10) ans = 2.3026 Anonymous functions can be saved as.mat files, just like any variable, and can be restored with the load command For example: to save the anonymous function ln, type: save my_ln_function ln A file named my_ln_function.mat is created, which contains the anonymous ln function Once the workspace is cleared, the ln function no longer exists, but it can be reloaded from the.mat file load my_ln_function It is possible to assign a function handle to any M-fi le function The command distance_handle = @(t) distance(t) assigns the handle distance_handle to the distance function Anonymous functions and the related function handles are useful in functions that require other functions as input

22 Function Functions MATLAB’s function functions have an odd, but descriptive name They are functions that require other functions as input One example of a MATLAB built-in function function is the function plot, fplot. This function requires two inputs: a function or a function handle, and a range over which to plot We can demonstrate the use of fplot with the function handle ln, defined as ln = @(x) log(x) The function handle can now be used as input to the fplot function: fplot(ln,[0.1, 10]) The result is shown in next slide We could also use the fplot function without the function handle We just need to insert the function syntax directly, as a string: fplot('log(x)',[0.1, 10]) The advantage to using function handles isn’t obvious from this example, but consider instead this anonymous function describing a particular fi fth- order polynomial: poly5 = @(x) -5*x.^5 + 400*x.^4 + 3*x.^3 + 20*x.^2 - x + 5;

23 Function handles can be used as input to a function functions, such as fplot

24 Continued…. Entering the equation directly into the fplot function would be awkward Using the function handle is considerably simpler. fplot(poly5,[-30,90]) The results are shown in next slide’s figure A wide variety of MATLAB functions accept function handles as input For example: the fzero function finds the value of x where f ( x ) is equal to 0. It accepts a function handle and a rough guess for x. We see that our fifth-order polynomial probably has a zero between 75 and 85, so a rough guess for the zero point might be x = 75. fzero(poly5,75) ans = 80.0081

25

26 Subfunctions More complicated functions can be created by grouping functions together in a single file as subfunctions These subfunctions can be called only from the primary function, so they have limited utility Subfunctions can be used to modularize code and to make the primary function easier to read Each MATLAB function M-fi le has one primary function The name of the M-file must be the same as the primary function name Thus, the primary function stored in the M-file my_function.m must be named my_function Subfunctions are added after the primary function, and can have any legitimate MATLAB variable name

27 Continued…. Figure shows a very simple example of a function that both adds and subtracts two vectors The primary function is named subfunction_demo The file includes two subfunctions: add and subtract

28 Continued…. In the editing window that the contents of each function are identified with a gray bracket Each code section can be either collapsed or expanded, to make the contents easier to read, by clicking on the + or - sign included with the bracket MATLAB uses the term “folding” for this functionality Folding can also be accessed from the “Text” menu on the menu bar

29 Example

30 Solution

31

32 Continued…. The primary function has no input and no output To execute the primary function, type the function name at the command prompt: sample_homework or select the save and run icon When the primary function executes, it calls the subfunctions, and the results are displayed in the command window, as follows: Problem 1 The squares of the input values are listed below 9 4 1 0 1 4 9 Problem 2 The percent cold work is ans = 0.7500 Problem 3 The change in potential energy is ans = 49 98 147

33 Continued…. In this example, the four functions are listed sequentially An alternate approach is to list the subfunction within the primary function, usually placed near the portion of the code from which it is called. This is called nesting When functions are nested, we need to indicate the end of each individual function with the end command

34


Download ppt "Recap Function M-files Syntax of Function M-Files Comments Multiple Input and Output Functions."

Similar presentations


Ads by Google