Getting Started with MATLAB   Search    Help Desk 

Scripts and Functions

MATLAB is 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 MATLAB's 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

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:



Typing the statement

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 name 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

You can see the file with

Here is the file.

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

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:

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

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:

Then interactively enter the statements:

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.

Command/Function Duality

MATLAB commands are statements like

Many commands accept modifiers that specify operands.

An alternate method of supplying the command modifiers makes them string arguments of functions.

This is MATLAB's "command/function duality." Any command of the form

can also be written in the functional form

The advantage of the functional approach comes when the string argument is constructed from other pieces. 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 string, to help build the file name.

The eval Function

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

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.

Vectorization

To obtain the most speed out of MATLAB, it's important to vectorize the algorithms in your M-files. Where other programming languages might use for or DO loops, MATLAB can use vector or matrix operations. A simple example involves creating a table of logarithms.

A vectorized version of the same code is

For more complicated code, vectorization options are not always so obvious. When speed is important, however, you should always look for ways to vectorize your algorithms.

Preallocation

If you can't 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.

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.

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:

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

Then plot the function with



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

To evaluate the function at the minimizer,

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

computes the area under the curve in the graph and produces

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

you will find one outside of the interval



[ Previous | Help Desk | Next ]