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

34
Lecture 27

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

Lecture 18

Lecture 27Recap Function M-filesSyntax of Function M-FilesCommentsMultiple Input and Output Functions

Functions with No Input or No OutputAlthough most functions need at least one input and return at least one output value, in some situations no inputs or outputs are requiredFor 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 expectedIf, from the command window, you type star then no values are returned, but a figure window opens showing a star drawn in polar coordinates

Continued.There are numerous built-in MATLAB functions that do not require any input.For example:A = clockreturns the current time:A =1.0e+003 *Columns 1 through 42.0050 0.0030 0.0200 0.0150Columns 5 through 60.0250 0.0277Also,A = pireturns the value of the mathematical constant p:A =3.1416However, 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 ==> ticToo many output argumentsThe tic function starts a timer going for later use in the toc functionDetermining the Number of Input and Output ArgumentsThere may be times when you want to know the number of input arguments or output values associated with a functionMATLAB provides two built-in functions for this purposeThe nargin function determines the number of input arguments in either a user-defined function or a built-in functionThe name of the function must be specified as a string, as, for example: innargin('sin')ans =1The remainder function, rem , requires two inputs; thus,nargin('rem')ans =2Continued.When nargin is used inside a user-defined function, it determines how many input arguments were actually enteredThis allows a function to have a variable number of inputsRecall graphing functions such as surfWhen 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 valuesThe nargin function allows the programmer to determine how to create the plot, based on the number of inputsContinued.The surf function is an example of a function with a variable number of inputsIf we use nargin from the command window to determine the number of declared inputs, there isnt one correct answerThe nargin function returns a negative number to let us know that a variable number of inputs are possible:nargin('surf')ans = -1The nargout function is similar to nargin , but it determines the number of outputs from a function:nargout('sin')ans = 1The number of outputs is determined by how many matrices are returned, not how many values are in the matrixWe 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 =1returns only one matrix, which has just two elements, as for example, inx = 1:10;size(x)ans = 1 10Continued.An example of a function with multiple outputs is max :nargout('max')ans =2When used inside a user-defined function, nargout determines how many outputs have been requested by the userConsider 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==1A = 'Twinkle twinkle little star';endIf we use nargout from the command window, as innargout('star1')ans = 1MATLAB tells us that one output is specified. If we call the function simply as star1nothing is returned to the command window, although the plot is drawnIf we callthe function by setting it equal to a variable, as inx = star1x = Twinkle twinkle little stara value for x is returned, based on the if statement embedded in the function, which used nargout to determine the number of output valuesLocal 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 returnsAny variables defined within the function exist only for the function to useFor 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 matricesa = x .*y;output = a;The variables a , x , y , and output are local variablesThey can be used for additional calculations inside the g function, but they are not stored in the workspaceTo confi rm this, clear the workspace and the command window and then call the g function:clear, clcg(10,20)The function returnsg(10,20)ans = 200Continued.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 workspaceThis 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 outputConsider 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 gravityg = 9.8 %meters per second squaredresult = 1/2*g*t.^2;Continued.The value of g must be included inside the functionIt doesnt matter whether g has or has not been used in the main programHow g is defined is hidden to the distance function unless g is specified inside the functionOf 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 gravityresult = 1/2*g*t.^2;Global Variables Unlike local variables, global variables are available to all parts of a computer programIn general, it is a bad idea to define global variablesHowever, 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 itConsider the distance function once again:function result = distance(t)%This function calculates the distance a falling object%travels due to gravityglobal Gresult = 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 GG = 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 functionCreating ToolBox of Functions When a function is called in MATLAB, the program first looks in the current folder to see if the function is definedIf it cant find the function listed there, it starts down a predefined search path, looking for a fi le with the function nameTo view the path the program takes as it looks for files, selectFile -> Set Path from the menu bar or typepathtool in the command window

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. Youll be prompted to either supply the folder location or browse to find it (shown in next slide)

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

Continued.Once a folder is added to the path, the change applies only to the current MATLAB session, unless changes are saved permanentlyClearly, permanent changes should never make to a public computerHowever, if someone else has made changes you wish to reverse, you can select the default button to return the search path to its original settingsThe 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 programConsulthelp 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 communityAnonymous Functions and Function Handles Normally, if there is trouble of creating a function, you will want to store it for use in other programming projectsHowever, 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 availablemuch as are variable namesonly until the workspace is clearedTo 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:

Continued.Anonymous functions can be used like any other functionfor example,ln(10)ans = 2.3026Anonymous functions can be saved as .mat files, just like any variable, and can be restored with the load commandFor example: to save the anonymous function ln , type:save my_ln_function lnA file named my_ln_function.mat is created, which contains the anonymous ln functionOnce the workspace is cleared, the ln function no longer exists, but it can be reloaded from the .mat file load my_ln_functionIt is possible to assign a function handle to any M-fi le functionThe commanddistance_handle = @(t) distance(t) assigns the handle distance_handle to the distance functionAnonymous functions and the related function handles are useful in functions that require other functions as input Function FunctionsMATLABs function functions have an odd, but descriptive nameThey are functions that require other functions as inputOne 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 plotWe can demonstrate the use of fplot with the function handle ln , defined asln = @(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 slideWe could also use the fplot function without the function handleWe just need to insert the function syntax directly, as a string:fplot('log(x)',[0.1, 10])The advantage to using function handles isnt 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;

Function handles can be used as input to a function functions, such as fplotContinued.Entering the equation directly into the fplot function would be awkwardUsing the function handle is considerably simpler.fplot(poly5,[-30,90])The results are shown in next slides figureA wide variety of MATLAB functions accept function handles as inputFor 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

Subfunctions More complicated functions can be created by grouping functions together in a single file as subfunctionsThese subfunctions can be called only from the primary function, so they have limited utilitySubfunctions can be used to modularize code and to make the primary function easier to readEach MATLAB function M-fi le has one primary functionThe name of the M-file must be the same as the primary function nameThus, 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 nameContinued.Figure shows a very simple example of a function that both adds and subtracts two vectorsThe primary function is named subfunction_demo The file includes two subfunctions: add and subtract

Continued.In the editing window that the contents of each function are identified with a gray bracketEach code section can be either collapsed or expanded, to make the contents easier to read, by clicking on the + or - sign included with the bracketMATLAB uses the term folding for this functionalityFolding can also be accessed from the Text menu on the menu barExample Solution

Continued.The primary function has no input and no outputTo execute the primary function, type the function name at the command prompt: sample_homework or select the save and run iconWhen the primary function executes, it calls the subfunctions, and the results are displayed in the command window, as follows:Problem 1The squares of the input values are listed below9 4 1 0 1 4 9Problem 2The percent cold work isans = 0.7500Problem 3The change in potential energy isans = 49 98 147Continued.In this example, the four functions are listed sequentiallyAn 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