User-Defined Functions Matlab Help

User-Defined Functions

FUNCTION FILE Another type of M-file.is a function file. Unlike a script file, all the variables in a function file are local. which means their values are available only within the function. Function files are useful when you need to repeat a set of commands several times. Function files are like functions in C, subroutines in FORTRAN and BASIC, and procedures in Pascal. They are the building blocks of larger programs. The first line in a function file must begin with a function, definition line that has a list of inputs and outputs. This line distinguishes a function M-fiIe from a script· M file. Its syntax is as follows: function [output variables] = function_name(input variables) Note that the output variables are enclosed in square brackets. while the input , variables must be enclosed with parentheses. The function_name should be” the same as the file name in which it is saved (with the. m extension). That is, if we mime a function drop, it should be saved in the file drop. m.The function is “called” by typing its name (for example, drop) at the command line. The word function in the function definition line must be  lowercase. Note also that even though MATLAB is case sensitive  y default. your computer’s operating system might not be case- sensitive with regard to file names. For example while

MATLAB would recognize Drop and drop as two different variables, your operating system might treat Drop. m and drop. ill as the same file.
Some Simple Function Examples
Now let us look at some simple user-defined functions. Remember that the name of the function M-file should be the same as the name of the function. Before naming a function, you can use the exist function to see if another function has the same name. Functions operate on variables within their own workspace (calIed local variables), which is separate from the workspace you access at the MATLAB command prompt. Consider the following user-defined function fun. function z = fun(x,y) u = 3*x; z = u + 6*y.”2; Note the use of a semicolon at the end of the lines. This prevents the values
of u and z from being displayed. Note also the use of the array  exponentiation operator ( . “). This enables the function to accept y as an array.Now consider what happens when you call this function in various ways in the Command window. Call the function with its output argument: »z = fun (3,7) z 303 The function uses x = 3 and y = 7 to compute z.Call the function without its output argument and try to access its value. You see an error message. »fun(3,7) ans 303 »z ??? Undefined function or variable r Z’ •Assign the output argument to another variable:
»q = fun(3,7)q = 303 You can suppress the output by putting a semicolon after the function call. For example, if you type q = fun (3 , 7) ; the value of q will be computed but not displayed.
The variables x and y are local to the function fun, so unless you  ass their values by naming them x and y, their values will not be available in the workspace outside the function. The variable u is also local to the function. For example,

»x 3;y = 7;
»q fun(x,y);
»x
x =
3
»y
y =
7
»u
??? Undefined function or variable ‘u’.Compare this to
»q = fun(3,7);
»x
??? Undefined function or variable “x ‘ .
>:::-y
??? Undefined function or variable ‘v ‘ .
Only ~e order of the arguments is important, not the names of the arguments:
»x = 7; y::= 3;
»z = fun(y,x)
A function may have more than one output. These are enclosed in square
brackets. For example, the function circle computes the area A and circumference
C of a circle, given its radius as an input argument.
function [A, C) = circle(r)
A = pi*r.”2;
C = 2*pL*r;
% This is equivalent to z
z =
303
You can use arrays as input “arguments:
»r = fun ([2:4) ,[7:9) )
r
300- 393 498
The function is called as follows, if r =4.
»[A, C) = circle(4)
A =
50.2655 i
f
/
C =
25.1327
fun(3,7)
If you omit an output argument, for example, and type [C]=circle(4),
MA!LAB displays the value(50.2635) of the first output variable (which is A), but names it C.

A function may have no input arguments and no output list. For example, the function show date computes and stores the date in’the variable today, and displays the value of today. ! function show_date today = date Variations in the Function Line The following examples show permissible variations in the format of the function line. The differences depend on whether there is no output, a single output,  r multiple outputs.

Capture

Example 1 is a function with one input and one output. The square brackets are optional when there is only one output (see example 2). Example 3 has one output and three inputs. Example 4 has two outputs and one input. Example 5 has no output ‘variable (for example •.a function that generates a plot). In such cases the equal sign may be omitted. Comment lines starting with the % sign can be placed anywhere in the function file. However,if you use help to obtain information about the function, MATLAB displays all comment lines immediately following the function definition line up’ to the first blank line or first executable line. The first comment line can be accessed by the look for command. .
We can call both built-in and user-defined functions .either with the out- ‘ put variables explicitly specified, as in examples 1 through 4, or without any output variables specified. For example, we can call the function square as square (side) if we are not interested in’its output variable area_square. (The function might perform some other operation ‘that we want to occur, such as toggling diary on or off.) Note that if we omit the semicolon at the end of the function call statement, the first variable in the output variable list w.ill be displayed using the default variable name ans..

Variations in Function Calls
The following function, called drop, computes a falling object’s velocity and distance dropped. The input variables are the acceleration g, the initial velocity Vo, and the elapsed time t. Note that we must use the element-by-element operations for any operations involving function inputs that are arrays. Here we  anticipate that t will be an array, so we use the element-by-element operator

function (dist,vel) = drop(g,vO,t);
% Computes the distance travelled and the
% velocity of a dropped object, as functions
% of g, the initial velocity vO, and the time t.
vel = g*t + va;
dist = 0.5*g*t.A2 + vO*t;

The following examples show various ways to call the function drop:

  1. The variable names used in the function definition may, but need not, be
    used when the function is called:
    a = 32.2;
    initial_speed = 10;
    time = 5;
    [feet_dropped,speed) drop(a,initial_speed,time)
  2. The input variables need not be assigned values outside the function prior to
    “the function call:
    (feet_dropped, speed) = drop(32.2,10,5)
  3. The inputs and outputs may be arrays:
    (feet_dropped,speed)=drop(32.2,10, (0:1:5))
    This function call produces the arrays feet_dropped and speed, each with
    six values corresponding to the six values of time in the array time.

Function Arguments

When invoking, or “calling” a function, the caller (either an entry from the key-board or a running file) must provide the function with any input data it needs by passing the data in the argument list. Data that needs to be returned to the caller is passed back in a list of output or return values. MATLAB uses two ways to pass argument data. It passes it by value (for example, as an array) or by an internal pointer to the data. If the function does not modify the value of the input data, it uses a more efficient pointer mechanism. If, however, the function modifies the value of the input data, MATLAB passes the argument by value. . If the function changes the value of an input variable, its value in the calling workspace might need be updated. This can be done by having the function return the updated value as an output argument. For example, consider the following function, which computes the radius of a circle whose area is a specified factor f of the original area.

function (r, A) = area_change (A, f)
A f*A;
r = short (A/pi) ;

If, on the other hand, we want to use the value of the new area but also preserve the value of the previous area, we could call the function as follows.

»[r new, Anew) = real change(A, f)

.After the function is called, the original value of A remains in the workspace

Local Variables
The names of the input variables given in the function-definition line are local to that function. This means that other variable names can be used when you call the function. All variables.inside a function are erased after the function finishes executing, except when same variable names appear in the output variable list used in the function call. For example, when using the drop function in a program, we can assign a value to the variable dist before the function call, and its value will be unchanged after the call because its name was not used in the output list of the call statement (the variable feet_dropped was used in the place of dist ).This is what is meant by the function’s variables being “local” to the function. This feature allows us to write generally useful functions using variables of our choice, without being concerned that the calling program uses the same variable names for other calculations. This means that our function files are “portable,” and need not be rewritten every time they are used in a different program.You might find the M-file Debugger to be useful for locating errors in function files. Run time errors in functions are more difficult to locate because the function’s local workspace is lost when the error forces a return to the MATLAB base workspace. The Debugger provides access to the function workspace, and allows
you to change values. It also enables you to execute lines one at a time and to set breakpoints, which are specific locations in the file where execution is temporarily halted. The applications in this text will probably not require use of the Debugger, which is useful mainly for very large programs, or programs containing nested functions (that is, functions that call other functions). For more information, see Section 4.7 in Chapter 4.

Global Variables
The global command declares certain variables global, and therefore their values are available to the basic workspace and to other functions that declare these variables global. The syntax to declare the variables a, x, and q is global a x q. Any assignment to those variables;. in any function or in the base workspace, is available to all the other functions declaring them global. If the global variable doesn’t exist the first time “you issue the global statement, it will be initialized to the empty matrix. If a variable with the same name as the global variable already exists in the current workspace, MATLAB issues a warning and changes the value of that variable to match the global. In a user-defined function, make the global command the first executable line. The decision whether or not to declare a variable global is not always clear cut. Often there is more than one effective way to solve a given problem. The following example illustrates this.

Applications
Some MATLAB commands act on functions. If the function of interest is not a simple function, it is more convenient to define the function in an M-file when using one of these commands.

‘Finding the Zeros of a Function

The root s function finds the zeros of polynomial functions only. Otherwise, you can use the fzero function to find the zero of a function of a single variable, which is denoted by x. One form of its
syntax is
fzero (‘functian., xO)

where function is a string containing the name of the function, and xO is a user-supplied guess for the zero. The f zero function returns a value of x that is near x u. It identifies only points where the function crosses the x-axis, not points where the function just touches the axis. For example, fzero ( , cas’ ,2) returns the value x = 1.5708.
The function fzero ( , function’ , x O) tries to find a zero of function near xO, if xO is a scalar. The value returned by fzero is near a point where function changes sign, or NaNif the search fails. In this case, the search terminates when the search interval is expanded until an In f ,NaN,or a complex value is found (fzero cannot find complex zeros). If xO is a vector of length two, fzero assumes that x Ois an interval where the sign of function (xO(1) ) differs from the sign of function (xO(2) ) . An error occurs if this is not true. Calling fzero with such an interval guarantees that fzero will return a value near a point where function changes sign. Plotting the function first is a good way to get a value for the vector xo. An alternate syntax is

[x,fval) = fzero (‘functiori’,xO)

This returns the value of function at the solution x. The syntax [x,fval, exitfIag) = fzero(‘function’ ,xO)

positive value of exit flag indicates that the function found a zero, hich is the value x. A negative value of exit f lag indicates that no interval was found with a sign change, or that aNaNor an In f function value was encountered during the search for an interval containing a sign change, or that a complex function value was encountered during the search for an interval containing a sign  hange. The fzero function finds a point where the function changes sign. If he function is continuous, this is also a point where the function has a value near zero. If the function is not continuous, f zero might return values that are discontinuous points instead of zeros. For example, x = fzera ( , tan’ ,1) returns x = 1.5708, a discontinuous point in tan(x ). Furthermore, the fzera command defines a zero as a point where the function crosses the x-axis. Points where the function touches, but does not cross; the

Plot of the function y = x +2e-x - 3.

Plot of the function y = x +2 e-x – 3.

x-axis at x = O. Because the function never crosses the x-axis, however, no zero is found. For functions with no valid zeros, fzero executes until Inf, NaN,or a complex value is detected.
To use this function to find the zeros of more complicated functions, t is more convenient to define the function in a function file. For example, if y = x + 2e-X – 3, define the following function file:

function y = f1(x)
y = x + 2*exp(-x) – 3

Functions can have more than one zero, so it helps to plot the function first and then use fzero to obtain an answer that is more accurate than the answer read off the plot. Figure 3;2-1 shows the plot of this function, which has two zeros, one near x = -0.5 and one near x = 3. To find the zero near x = -0.5, type x = fzero ( jfl’, -0.5). The answer isx = -0.5831. To find the zero near x = 3, type x./= fzero ( , £1′ ,3). The answer is x = 2.8887

Minimizing a Function of One Variable The f mind function finds the minimum of a function of a single variable, which is denoted by x. One form of its syntax is

f mind (‘function’, xl, x2)

where function is a string containing the name of the function. The fminbnd function returns a value of x that minimizes the Junction in the interval xl x x2. For example, fminbnd ( , cos’ , 0,4)’ returns the valut x = 3.1416.However, to use this function to find the minimum of more-complicated functions, it is more convenient to define the function in a function file. For example, if y = I – »e=, define the following function file:

function y = f2(x)
y = 1- x. *exp (-x) ;

To find the value of x that gives a minimum of y for 0·:::: x -f:: 5, type’ x = frnd nbnd ( , f 2 ‘ , 0, 5) . The answer is x = 1.To find the ‘minimum value of y, type y = f 2 (x) . The result is y = O. 6321.
, The alternate syntax

[x,fval] = fminbnd (‘function’ ,x1,x2)

returns the value of function at the solution x. The syntax

[x,fval, exit flag] = ftHilpnd'(‘function’ ,x1·,x2)·

.return avalue of ex i t f ta:g wi¢ desr.b the exit condifn of f minbd. . i The.value ex i t.flag = 1 iridicates that the function convergedtoa solution x a value otherthan ex i, t f Laq = 1 indicates hat the fl,locticiodid not converge toasolution 1
To find the maximum of ·aJ,ion us1 fmi nbnd function with he negative of the function of interest. For example, to·find the maximum of y = =: over the interval 0 x 5, you must define function file as follows:

function y= f3(x)
y = -x , *exp (-x) ;

Typing fminbnd ( , f3′ , 0, 5) gives the result x = 1. The function y = xe:” has a maximum at x = 1. .’Whenever we use a minimization technique, we should check to make sure that the solution is a true minimum. For example, consider the following .polynomial:

y = 0.025xs – 0.0625×4 – 0.333×3 +x2

Its plot is shown in Figure 3.2-2. The function has two minimum points in the interval -1 < x < 4. The minimum near x = 3 is called a relative or local minimum because it forms a valley whose lowest point is higher than the minimum at x = O. The rriinirnum at x = 0 is the true minimum-and is also called the global minimum. If we specify the interval -1 :::x: ::::4 by typing

»x = fminbnd(‘O.02S*x.AS-O.062S*x.A4-0.333*x.A3+x.A2’,-l,4)

MATLAB gives the answer x = 2. 0438e-006, which is essentially 0, the true minimum point. If we specify the interval 0.1 ::::x ::::2.5, MATLAB gives the answer x = 0.10 a 1, which corresponds to the minimum value of yon the

Plot of the function y = O.025xs - O.0625x4 - O.333x3 +x2.

Plot of the function y = O.025xs – O.0625×4 – O.333×3 +x2.

interval 0.1 ~ x ~ 2.5. Thus we will miss the true minimum point if our specified interval does not include it.’ .
Also, fm:i,.nbndcan give incorrect answers.ja earlier versions of MATLAB, if we specified.the interval 1 ~ x ~ 4, MATLAB gave the answer x = 2. 8236, which corresponds to the “valley” shown in the plot, but which-is not the minimum point on the interval 1 ~ x ~ 4. On this interval the minimum point is at the bodridary x = 1, and MATLAB 7 correctly computes this answer. The fminbnd procedure now looks for a minimum point corresponding to a zero slope, and it
looks at the function values at the boundaries of the specified interval for x. In this example, MATLAB 7 identified the true rliinimum at the boundary, but in other problems it might incorrectly identify a local minimum as the true minimum. No one has yet developed a numerical minimization method that works for every possible function. Therefore, we must use any such method with care. In practice, the best use of the fminbnd function is to determine precisely the location of a minimum point whose approximate location was found by other means, such as by’ plotting the function.

Minimizing a Function of Severa! Variables To find the minimum of a function of more than one variable, use the fminsearch function. One form or its syntax is

fmfnsear ch ( , funct ~’on’; xO)”

where funct ion is a string containing the name of the function. The vector
xO is a guess that must be supplied by the user. For example, to minimize the
function f = xe-x2

y2
, we first define it in an M-file, using the vector x whose
elements are x (1) = x and x (2) = y.

function f = f4(x)
f = x(1).*exp(-x(l).”2-x(2).”2);

Suppose we guess that the minimum is near x = y = O.The session is

»fminsearch ( , f4′ , [0,0) )
ans =
-0.7071 0.000

Thus the minimum occurs at x = -0.7071, Y = O.
The alternate syntax

[x,fval) = fminsearch(‘function’ ,xO

returns the value of function at the solution x. The syntax

[x,fval, exitflag) = fminsearch(‘function’ ,xl,x2)

returns a value of exi t f lag, which describes the exit condition of
fmins earch. The value exi t flag = 1 indicates that the function converged to a solution x; a value other than exi t flag = 1 indicates that the function did not converge to a solution.not converge to a solution.

The fminsearch function can often handle discontinuities, particularly if they do not occur nearthe solution. The fminsearch function might give local solutions only, and it minimizes over the real numbers only; that is, x must consist of real variables only and the function must return real numbers only. When x has complex variables, they must be split into real and imaginary parts.

Minimization and root-finding functions

Minimization and root-finding functions

Minimization and root-finding functions

Minimization and root-finding functions

Design Optimization
One way to improve engineering designs is by formulating the equations describing the design in the form of a minimization or maximization problem. This approach is called design optimization. Examples of quantities we would like to minimize are energy consumption and construction materials. Items we would like to maximize are useful life and capacity (such as the vehicle weight hat can be supported by a bridge). The following example illustrates the concept of design optimization.

The f z era, frni.nbnd, and fmins earch functions have alternative forms not described here. With these forms you can specify the accuracy required for the sol~t~~n,as well as the number ofsteps to use before stopping. Use the help facility to find out more about these functions .

Test Your Understanding
T3.2-1 The, equation e-O.
2x sin(x + 2) = 0.1 has three solutions in the interval O. <.~.<10: Find these three solutions.
T3.2-2 The function y = 1 + e-O. 2x sin(x + 2) has two minimum points in the interval 0 < x < 10. Find the values of x and y at each minimum.
T3.2-3 ..Find the depth d and angle 0 to\minimize the perimeter length ofcthe channels~own in Figure 3.2-3′ t<;> provide an area of 200 ft2. (Answer: d = 10.74′;;? ft, 0 = W.)

Posted on July 27, 2015 in function and files

Share the Story

Back to Top
Share This