Products & Services Industries Academia Support User Community Company

Learn more about MATLAB   

Scripts and Functions

Overview

The MATLAB product provides a powerful programming language, as well as an interactive computational environment. Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB function or command.

There are two kinds of M-files:

If you're a new MATLAB programmer, just create the M-files that you want to try out in the current directory. As you develop more of your own M-files, you will want to organize them into other directories and personal toolboxes that you can add to your MATLAB search path.

If you duplicate function names, MATLAB executes the one that occurs first in the search path.

To view the contents of an M-file, for example, myfunction.m, use

type myfunction

Scripts

When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot.

For example, create a file called magicrank.m that contains these MATLAB commands:

% Investigate the rank of magic squares
r = zeros(1,32);
for n = 3:32
   r(n) = rank(magic(n));
end
r
bar(r)

Typing the statement

magicrank

causes MATLAB to execute the commands, compute the rank of the first 30 magic squares, and plot a bar graph of the result. After execution of the file is complete, the variables n and r remain in the workspace.

Functions

Functions are M-files that can accept input arguments and return output arguments. The names of the M-file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.

A good example is provided by rank. The M-file rank.m is available in the directory

toolbox/matlab/matfun

You can see the file with

type rank

Here is the file:

function r = rank(A,tol)
%   RANK Matrix rank.
%   RANK(A) provides an estimate of the number of linearly
%   independent rows or columns of a matrix A.
%   RANK(A,tol) is the number of singular values of A
%   that are larger than tol.
%   RANK(A) uses the default tol = max(size(A)) * norm(A) * eps.

s = svd(A);
if nargin==1
   tol = max(size(A)') * max(s) * eps;
end
r = sum(s > tol);

The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments. In this case, there are up to two input arguments and one output argument.

The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines are printed when you type

help rank

The first line of the help text is the H1 line, which MATLAB displays when you use the lookfor command or request help on a directory.

The rest of the file is the executable MATLAB code defining the function. The variable s introduced in the body of the function, as well as the variables on the first line, r, A and tol, are all local to the function; they are separate from any variables in the MATLAB workspace.

This example illustrates one aspect of MATLAB functions that is not ordinarily found in other programming languages—a variable number of arguments. The rank function can be used in several different ways:

rank(A)
r = rank(A)
r = rank(A,1.e-6)

Many M-files work this way. If no output argument is supplied, the result is stored in ans. If the second input argument is not supplied, the function computes a default value. Within the body of the function, two quantities named nargin and nargout are available that tell you the number of input and output arguments involved in each particular use of the function. The rank function uses nargin, but does not need to use nargout.

Types of Functions

MATLAB offers several different types of functions to use in your programming.

Anonymous Functions

An anonymous function is a simple form of the MATLAB function that does not require an M-file. It consists of a single MATLAB expression and any number of input and output arguments. You can define an anonymous function right at the MATLAB command line, or within an M-file function or script. This gives you a quick means of creating simple functions without having to create M-files each time.

The syntax for creating an anonymous function from an expression is

f = @(arglist)expression

The statement below creates an anonymous function that finds the square of a number. When you call this function, MATLAB assigns the value you pass in to variable x, and then uses x in the equation x.^2:

sqr = @(x) x.^2;

To execute the sqr function defined above, type

a = sqr(5)
a =
   25

Primary and Subfunctions

All functions that are not anonymous must be defined within an M-file. Each M-file has a required primary function that appears first in the file, and any number of subfunctions that follow the primary. Primary functions have a wider scope than subfunctions. That is, primary functions can be invoked from outside of their M-file (from the MATLAB command line or from functions in other M-files) while subfunctions cannot. Subfunctions are visible only to the primary function and other subfunctions within their own M-file.

The rank function shown in the section on Functions is an example of a primary function.

Private Functions

A private function is a type of primary M-file function. Its unique characteristic is that it is visible only to a limited group of other functions. This type of function can be useful if you want to limit access to a function, or when you choose not to expose the implementation of a function.

Private functions reside in subdirectories with the special name private. They are visible only to functions in the parent directory. For example, assume the directory newmath is on the MATLAB search path. A subdirectory of newmath called private can contain functions that only the functions in newmath can call.

Because private functions are invisible outside the parent directory, they can use the same names as functions in other directories. This is useful if you want to create your own version of a particular function while retaining the original in another directory. Because MATLAB looks for private functions before standard M-file functions, it will find a private function named test.m before a nonprivate M-file named test.m.

Nested Functions

You can define functions within the body of any M-file function. These are said to be nested within the outer function. A nested function contains any or all of the components of any other M-file function. In this example, function B is nested in function A:

function x = A(p1, p2)
...
B(p2)
   function y = B(p3)
   ...
   end
...
end

Like other functions, a nested function has its own workspace where variables used by the function are stored. But it also has access to the workspaces of all functions in which it is nested. So, for example, a variable that has a value assigned to it by the primary function can be read or overwritten by a function nested at any level within the primary. Similarly, a variable that is assigned in a nested function can be read or overwritten by any of the functions containing that function.

Function Overloading

Overloaded functions act the same way as overloaded functions in most computer languages. Overloaded functions are useful when you need to create a function that responds to different types of inputs accordingly. For instance, you might want one of your functions to accept both double-precision and integer input, but to handle each type somewhat differently. You can make this difference invisible to the user by creating two separate functions having the same name, and designating one to handle double types and one to handle integers. When you call the function, MATLAB chooses which M-file to dispatch to based on the type of the input arguments.

Global Variables

If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function. Although it is not required, using capital letters for the names of global variables helps distinguish them from other variables. For example, create an M-file called falling.m:

function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;

Then interactively enter the statements

global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)');

The two global statements make the value assigned to GRAVITY at the command prompt available inside the function. You can then modify GRAVITY interactively and obtain new solutions without editing any files.

Passing String Arguments to Functions

You can write MATLAB functions that accept string arguments without the parentheses and quotes. That is, MATLAB interprets

foo a b c

as

foo('a','b','c')

However, when you use the unquoted form, MATLAB cannot return output arguments. For example,

legend apples oranges

creates a legend on a plot using the strings apples and oranges as labels. If you want the legend command to return its output arguments, then you must use the quoted form:

[legh,objh] = legend('apples','oranges');

In addition, you must use the quoted form if any of the arguments is not a string.

Constructing String Arguments in Code

The quoted form enables you to construct string arguments within the code. The following example processes multiple data files, August1.dat, August2.dat, and so on. It uses the function int2str, which converts an integer to a character, to build the filename:

for d = 1:31
   s = ['August' int2str(d) '.dat'];
   load(s) 
   % Code to process the contents of the d-th file
end

The eval Function

The eval function works with text variables to implement a powerful text macro facility. The expression or statement

eval(s)

uses the MATLAB interpreter to evaluate the expression or execute the statement contained in the text string s.

The example of the previous section could also be done with the following code, although this would be somewhat less efficient because it involves the full interpreter, not just a function call:

for d = 1:31
   s = ['load August' int2str(d) '.dat'];
   eval(s)  
   % Process the contents of the d-th file
end

Function Handles

You can create a handle to any MATLAB function and then use that handle as a means of referencing the function. A function handle is typically passed in an argument list to other functions, which can then execute, or evaluate, the function using the handle.

Construct a function handle in MATLAB using the at sign, @, before the function name. The following example creates a function handle for the sin function and assigns it to the variable fhandle:

fhandle = @sin;

You can call a function by means of its handle in the same way that you would call the function using its name. The syntax is

fhandle(arg1, arg2, ...);

The function plot_fhandle, shown below, receives a function handle and data, generates y-axis data using the function handle, and plots it:

function x = plot_fhandle(fhandle, data)
plot(data, fhandle(data))

When you call plot_fhandle with a handle to the sin function and the argument shown below, the resulting evaluation produces a sine wave plot:

plot_fhandle(@sin, -pi:0.01:pi)

Function Functions

A class of functions called "function functions" works with nonlinear functions of a scalar variable. That is, one function works on another function. The function functions include

MATLAB represents the nonlinear function by a function M-file. For example, here is a simplified version of the function humps from the matlab/demos directory:

function y = humps(x)
y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6;

Evaluate this function at a set of points in the interval 0 ≤ x ≤ 1 with

x = 0:.002:1;
y = humps(x);

Then plot the function with

plot(x,y)

The graph shows that the function has a local minimum near x = 0.6. The function fminsearch finds the minimizer, the value of x where the function takes on this minimum. The first argument to fminsearch is a function handle to the function being minimized and the second argument is a rough guess at the location of the minimum:

p = fminsearch(@humps,.5)
p =
    0.6370

To evaluate the function at the minimizer,

humps(p)

ans =
   11.2528

Numerical analysts use the terms quadrature and integration to distinguish between numerical approximation of definite integrals and numerical integration of ordinary differential equations. MATLAB quadrature routines are quad and quadl. The statement

Q = quadl(@humps,0,1)

computes the area under the curve in the graph and produces

Q =
   29.8583

Finally, the graph shows that the function is never zero on this interval. So, if you search for a zero with

z = fzero(@humps,.5)

you will find one outside the interval

z =
   -0.1316

Vectorization

One way to make your MATLAB programs run faster is to vectorize the algorithms you use in constructing the programs. Where other programming languages might use for loops or DO loops, MATLAB can use vector or matrix operations. A simple example involves creating a table of logarithms:

x = .01;
for k = 1:1001
   y(k) = log10(x);
   x = x + .01;
end

A vectorized version of the same code is

x = .01:.01:10;
y = log10(x);

For more complicated code, vectorization options are not always so obvious.

Preallocation

If you cannot vectorize a piece of code, you can make your for loops go faster by preallocating any vectors or arrays in which output results are stored. For example, this code uses the function zeros to preallocate the vector created in the for loop. This makes the for loop execute significantly faster:

r = zeros(32,1);
for n = 1:32
    r(n) = rank(magic(n));
end

Without the preallocation in the previous example, the MATLAB interpreter enlarges the r vector by one element each time through the loop. Vector preallocation eliminates this step and results in faster execution.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS