Chapter 6. Writing and calling functions
In this chapter we discuss how to structure a program with multiple source code files. First, an
explanation of how code files work in MATLAB is presented. In compiled languages such as
FORTRAN, C, or C++, code can be stored in one or more source files that are linked together
to form a single executable at the time of compilation. MATLAB, being an interpreted
language, deals with multiple source files in a more open-ended manner. MATLAB code is
organized into ASCII files carrying the extension .m (also known as m-files). MATLAB 6 has an
integrated word processing and debugging utility that is the preferred mode of editing m-files,
although other ASCII editors such as vi or emacs may also be used.
There are two different kinds of m-files. The simplest, a script file, is merely a collection of
MATLAB commands. When the script file is executed by typing its name at the interactive
prompt, MATLAB reads and executes the commands within the m-file just as if one were
entering them manually. It is as if one were cutting and pasting the m-file contents into the
MATLAB command window. The use of this type of m-file is outlined in section 6.1.
The second kind of m-file, discussed in section 6.2, contains a single function that has the
same name as that of the m-file. This m-file contains an independent section of code with a
clearly defined input/output interface; that is, it can be invoked by passing to it a list of
dummy arguments arg1, arg2, .
.. and it returns as output the values out1, out2, .
... The first
non-commented line of a function m-file contains the function header, which is of the form :
..] = filename(arg1,arg2,.
The m-file ends with the command return, which returns the program execution to the place
where the function was called. The function code is executed whenever, either at the
interactive command prompt or within another m-file, it is invoked with the command :
..] = filename(var1,var2,.
with the mapping of input to dummy arguments : arg1 = var1, arg2 = var2, etc. Within the
function body, output values are assigned to the variables out1, out2, etc. When return is
encountered, the current values of out1, out2, .
.. are mapped to the variables outvar1,
.. at the point where the function was called. MATLAB allows much latitude in writing
functions with variable length argument and output variable lists. For example, the function
could also be invoked by the command :
outvar1 = filename(var1,var2,.
in which case only a single output variable is returned, containing on exit the value of the
function variable out1. The input and output arguments may be strings, scalar numbers,
vectors, matrices, or more advanced data structures.
Why use functions? As is well known from every computer science course, splitting a large