MATLAB Functions: Nature and Use

Topics relating to use and creation of functions:
[Back to main page] [Back to language features]

Purpose and role of a function in MATLAB programming

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, sin, exp, log and so forth. These functions compartmentalize the computation of specific mathematical functions, relieving you of having to explicitly carry out the computations every time you need to have access to those functions.

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

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.


Why use functions in MATLAB?

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

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

  1. 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.

  2. 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.


Elements and syntax of a MATLAB function

All functions have the following elements:

The function definition line

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 fname.m. The function is to take input arguments (in1,in2,...,inM) and produce output arguments (out1,out2,... ,outN). The number of inputs (M) and outputs (N) can be zero or any positive integer.

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

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

The key syntax elements of the definition line are

  1. The word function

    The keyword function must be the first word on the definition line. The keyword function differentiates 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.

  2. 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 nargout which provides the number of output arguments used in the call to the function.

  3. 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.

  4. 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 nargin which may be used by the function to determine the number of input arguments that were provided in the call to the function.

H1 help lines

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.

Body of the function

The contents of a function are really no different from those of a script. Any valid MATLAB command may be used within a function. It is up to the programmer (you) to decide the proper order of the commands in the function. The only guiding principles are
  1. A function executes sequentially from the first valid line after the definition line to the end of the Mfile.

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

  3. 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.


Evolution: Function handles and anonymous functions

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 function functions - functions that use functions as inputs (root finding, integration, ODE and PDE solutions being the big ones built into MATLAB). In making this separation, the function handle gives a very flexible way to create and use the input function in function functions. And that is a good thing.


[Back to main page] [Back to language features]
Comments? Contact Jim Maneval at