Programming Previous page   Next Page

M-File Functions

Functions are program routines, usually implemented in M-files, that accept input arguments and return output arguments. They operate on variables within their own workspace. This workspace is separate from the workspace you access at the MATLAB command prompt.

The Function Workspace

Each M-file function has an area of memory, separate from the MATLAB base workspace, in which it operates. This area, called the function workspace, gives each function its own workspace context.

While using MATLAB, the only variables you can access are those in the calling context, be it the base workspace or that of another function. The variables that you pass to a function must be in the calling context, and the function returns its output arguments to the calling workspace context. You can, however, define variables as global variables explicitly, allowing more than one workspace context to access them.

Simple Function Example

The average function is a simple M-file that calculates the average of the elements in a vector:

Try entering these commands in an M-file called average.m. The average function accepts a single input argument and returns a single output argument. To call the average function, enter


Previous page  M-File Scripts and Functions Types of Functions Next page

© 1994-2005 The MathWorks, Inc.