| On this page… |
|---|
Scripts are the simplest kind of M-file because they have no input or output arguments. They are useful for automating series of MATLAB commands, such as computations that you have to perform repeatedly from the command line.
Scripts share the base workspace with your interactive MATLAB session and with other scripts. They operate on existing data in the workspace, or they can create new data on which to operate. Any variables that scripts create remain in the workspace after the script finishes so you can use them for further computations. You should be aware, though, that running a script can unintentionally overwrite data stored in the base workspace by commands entered at the MATLAB command prompt.
These statements calculate rho for several trigonometric functions of theta, then create a series of polar plots:
% An M-file script to produce % Comment lines
% "flower petal" plots
theta = -pi:0.01:pi; % Computations
rho(1,:) = 2 * sin(5 * theta) .^ 2;
rho(2,:) = cos(10 * theta) .^ 3;
rho(3,:) = sin(theta) .^ 2;
rho(4,:) = 5 * cos(3.5 * theta) .^ 3;
for k = 1:4
polar(theta, rho(k,:)) % Graphics output
pause
end
Try entering these commands in an M-file called petals.m. This file is now a MATLAB script. Typing petals at the MATLAB command line executes the statements in the script.
After the script displays a plot, press Enter or Return to move to the next plot. There are no input or output arguments; petals creates the variables it needs in the MATLAB workspace. When execution completes, the variables (i, theta, and rho) remain in the workspace. To see a listing of them, enter whos at the command prompt.
Functions are program routines, usually implemented in M-files, that accept input arguments and return output arguments. You define MATLAB functions within a function M-file; that is, a file that begins with a line containing the function key word. You cannot define a function within a script M-file or at the MATLAB command line.
Functions always begin with a function definition line and end either with the first matching end statement, the occurrence of another function definition line, or the end of the M-file, whichever comes first. Using end to mark the end of a function definition is required only when the function being defined contains one or more nested functions.
Functions operate on variables within their own workspace. This workspace is separate from the base workspace; the workspace that you access at the MATLAB command prompt and in scripts.
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. You can also evaluate any MATLAB statement using variables from either the base workspace or the workspace of the calling function using the evalin function. See Extending Variable Scope for more information.
The average function is a simple M-file that calculates the average of the elements in a vector:
function y = average(x)
% AVERAGE Mean of vector elements.
% AVERAGE(X), where X is a vector, is the mean of vector
% elements. Nonvector input results in an error.
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))
error('Input must be a vector')
end
y = sum(x)/length(x); % Actual computation
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
z = 1:99;
average(z)
ans =
50
MATLAB provides the following types of functions. Each function type is described in more detail in a later section of this documentation:
The Primary M-File Functions is the first function in an M-file and typically contains the main program.
Subfunctions act as subroutines to the main function. You can also use them to define multiple functions within a single M-file.
Nested Functions are functions defined within another function. They can help to improve the readability of your program and also give you more flexible access to variables in the M-file.
Anonymous Functions provide a quick way of making a function from any MATLAB expression. You can compose anonymous functions either from within another function or at the MATLAB command prompt.
Overloaded Functions are useful when you need to create a function that responds to different types of inputs accordingly. They are similar to overloaded functions in any object-oriented language.
Private Functions give you a way to restrict access to a function. You can call them only from an M-file function in the parent directory.
You might also see the term function functions in the documentation. This is not really a separate function type. The term function functions refers to any functions that accept another function as an input argument. You can pass a function to another function using a function handle.
When writing and saving your M-file functions, you have several options on how to organize the functions within the M-file, and also where in your directory structure you want to save them. Be sure to place your function M-files either in the directory in which you plan to run MATLAB, or in some other directory that is on the MATLAB path.
Use this table as a general guide when creating and saving your M-files:
| If your program or routine . . . | then . . . |
|---|---|
| Requires only one function | Make it a single (primary) function in the M-file. |
| Also requires subroutines | Make each subroutine a subfunction within same M-file as the primary. |
| Is for use only in the context of a certain function | Nest it within the other function. Nested functions also offer wider access to variables within the function. |
| Is a constructor or method of a MATLAB class | Put the M-file in a MATLAB class directory. |
| Is to have limited access | Put the M-file in a private subdirectory. |
| Is part of a group of similar functions or classes | Put the M-file in a package subdirectory. |
If necessary, you can work around some of the constraints regarding function access by using function handles. You might find this useful when debugging your functions.
If you need to know what other functions and scripts your program is dependent upon, use one of the techniques described below.
For a simple display of all M-files referenced by a particular function, follow these steps:
Type clear functions to clear all functions from memory (see Note below).
Execute the function you want to check. Note that the function arguments you choose to use in this step are important, because you can get different results when calling the same function with different arguments.
Type inmem to display all M-files that were used when the function ran. If you want to see what MEX-files were used as well, specify an additional output:
[mfiles, mexfiles] = inmem
For a much more detailed display of dependent function information, use the depfun function. In addition to M-files, depfun shows which built-ins and classes a particular function depends on:
[list, builtins, classes] = depfun('strtok.m');
list
list =
'D:\matlabR14\toolbox\matlab\strfun\strtok.m'
'D:\matlabR14\toolbox\distcomp\toChar.m'
'D:\matlabR14\toolbox\matlab\datafun\prod.m'
'D:\matlabR14\toolbox\matlab\datatypes\@opaque\char.m'
.
.
.
![]() | Working with M-Files | Calling Functions | ![]() |

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 |