Topics relating to use and creation of functions:

- The role of functions
- Why use functions?
- The syntax of a function
- Function handles and anonymous functions

[Back to main page] [Back to language features]

A function is a programming device that lets you compartmentalize and
tightly control the way in which computations are done in MATLAB. For example,
you probably are aware of the built-in functions in MATLAB such as
` sqrt`,

Functions permit you to view the flow of logic through a computation at a higher level of abstraction. For example, consider taking the square-root of a number. There are many approaches to this computational problem but from the point of view of getting and using the square-root of a number, the method of computation is not really of primary concern. Rather, knowing that the command

w = sqrt(3)

will compute the value of the square-root of 3 and then assign the
result to the variable called
** w** lets you focus on the assignment process and not the
details of getting the value used in the assignment.

This higher level of abstraction is illustrated in the
figure below which shows the process of using a function (with
the square-root function as an example):

An input-output view of a MATLAB function

Note that what goes on inside the function is
not known *explcitly*. The function is a black-box, from this point
of view. However, what is important is that the function will take a
number as **input** and produce, as a result of some computational
procedure, an
**output** which is the square root of that number. Other ways of
saying the same thing are

- A function transforms the inputs to the outputs
- A function operates on the inputs to produce outputs
- A function takes "givens" and produces "finds"
- A function takes data and produces information
- A function is a "button" you push that gives you a "result"
- A function is a verb that acts on a noun (the input) to produce a result (the output)

The higher level ideas of transformation and operation lend themselves
more easily to the development of programs (scripts, other functions) that
implement problem-solving algorithms.

The primary reason for using a function is to compartmentalize a particular computation. The computation of mathematical functions (e.g., Bessel functions, trigonometric functions, exponential functions or statistical distributions) is one important reason to "compartmentalize". When was the last time you worried about what the SIN button on your calculator actually did? You were probably more interested in the result of the function rather than how the function was executed.

You can generalize this idea to the compuation of things of more direct use to your professional life. For example, in chemical engineering, you might want to "compartmentalize" activities like

- Computing the vapor-pressure of a pure liquid at a given temperature
- Finding the specific volume of a gas, given a temperature and pressure
- Finding the heat-transfer coefficient for flow past a bundle of tubes

While each of these tasks involves a good deal of detail, they are each "basic" to the chemical engineering profession in the same way that mathematical functions are "basic" to mathematicians.

Beyond compartmentalization, functions play two imporant roles in MATLAB programing

- Functions are a very important basis for any sort of advanced or complex
programming project. The control and organization offered by the
input-output model is key to getting the reliable computations required in
engineering practice.

- Many of the advanced numerical features of MATLAB (the differential
equations solvers, root finders and integrators) take
*functions*as inputs. Hence knowing how to create functions is a pre-requisite for using these advanced tools.

All functions have the following elements:

- Line 1: function definition line
- Lines 2-N: H1 help lines
- Lines N+1-end: Body of the function

All function Mfiles should start with a function definition line. The general form of this line is

function [out1,out2,... ,outN] = fname(in1,in2,...,inM)

The definition line sets out the "contract" for the function. The
function will be called ` fname` and is stored in the file

**Examples**: Identify the name of the function, the number of inputs and
the number of outputs from each of the following definition lines.

**function [A,interest,principal] = loan(P,rate,term)****function P = srk(V,T,param)****function polyplot(x,y,n)**

The key syntax elements of the definition line are

- The word
**function**

The keyword

**function***must*be the first word on the definition line. The keyworddifferentiates a function Mfile from a script Mfile and so it is important to include it in an Mfile destined to be a function Mfile. There should be a space between the word`function`and the rest of the definition line.`function`

- Square brackets (
) around the output argument list**[ ]**

The list of variable names in the square brackets is called the*output argument list*. There can be any number of arguments (even zero). The function must assign some value to the variables in this list - otherwise they are set to empty arrays (in version 4) or a warning is generated (version 5). There are no restrictions on the output arguments with regard to shape or size.There is a permanent variable called

which provides the number of output arguments used in the call to the function.`nargout`

- The name of the function

Any valid MATLAB variable name can be a valid MATLAB function name. For consistency and to keep errors to a minimum, the name of the file containing the code for the function should be the same as the name of the function. For example, the first example given above would be stored in the file called`loan.m`while the third would be stored in`polyplot.m`.**Do not use the name of a built-in function as the name of a function you create.**

- Parentheses (
) around the input argument list.**()**

The parentheses after the function name define the*input argument list*. Unless global variables are used, you should make sure that the function can carry out all computations on the basis of the content of the input variables alone. Any number of inputs is allowed (even zero). As with the output arguments, there is no constraint on the sizes or shapes of the input arguments.There is a permanent variable called

which may be used by the function to determine the number of input arguments that were provided in the call to the function.**nargin**

The first unbroken set of comment lines that follow the function definition line are called the H1 help lines. These lines are displayed when a user issues the on-line help command for the function. For example, the following portion of a function provides an idea of how to structure the H1 help information.

function polyplot(x,y,n) %POLYPLOT Fit and plot a polynomial of degree n to a set of data (x,y) % % ployplot(x,y,n) fits an nth order polynomial to a set of x-y data and % plots the data and the fit on the same set of axes, using symbols for % the data and a solid line for the fit. % % If n is omitted, n = 1 is assumed. % This comment is not part of the H1 help section since a blank line % separates it from the prior comment lines

If you put these lines in the file `polyplot.m`, then typing

>> help polyplot

will generate the output

POLYPLOT Fit and plot a polynomial of degree n to a set of data (x,y) ployplot(x,y,n) fits an nth order polynomial to a set of x-y data and plots the data and the fit on the same set of axes, using symbols for the data and a solid line for the fit. If n is omitted, n = 1 is assumed.

Note that once a blank, un-commented line is encountered, no further information is displayed to the screen.

An effort should be made to write succinct, informative help lines for yourself and for others using the functions you write. For example, provide a summary of the syntax (input and output arguments) and notify the user of any default behavior.

- A function executes sequentially from the first valid line after the
definition line to the end of the Mfile.

- Only the information contained within the input arguments can be
assumed known at the start of calculations in the function.

- All output arguments must be calculated from the input arguments within
the function. [
*Exception*: You can use global variables to provide input that supplements the input arguments. I would not encourage you to use global variables in your code, if at all possible. These variables can cause major headaches as your programs become more complicated and sophisticated.]

Within these guidelines, much is possible in the realm of programming
with a function Mfile.

Since version 5, MATLAB has enhanced and evolved its handling of functions
through the addition of function handles, a data-type that contains the state of
a function in a convenient and transportable wrapper. Function handles and
their creation by the ` @` is probably best understood (at least at
the beginning) in terms of how they can be used.

My take on how to use function handles and anonymous function (a strange name)
with ` fzero` to find the roots of a user-defined function is given
here. In short, function handles provide
a mechanism that cleanly separates the inputs to all of the functions involved
in

[Back to main page] [Back to language features]

Comments? Contact Jim Maneval at