| Contents | Index |
| On this page… |
|---|
Scripts are the simplest kind of program 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.
For example, these statements calculate rho for several trigonometric functions of theta, then create a series of polar plots:
% A 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 a 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 (k, theta, and rho) remain in the workspace. To see a listing of them, enter whos at the command prompt.
Scripts share the base workspace with your interactive MATLAB session and with other scripts. For more information, see Base and Function Workspaces.
The main difference between a script and a function is that a function accepts input from and returns output to its caller, whereas scripts do not. You define MATLAB functions in a file that begins with a line containing the function key word. You cannot define a function within a script 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 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.
The average function is a simple 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 a 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
Each function in a file 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. For more information, see Base and Function Workspaces.
MATLAB provides the following types of functions. Each function type is described in more detail in a later section of this documentation:
The primary function is the first function in a program 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 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 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 a function in the parent folder.
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 functions, you have several options on how to organize the functions within the file, and also where in your folder structure you want to save them. Be sure to place your function files either in the folder in which you plan to run MATLAB, or in some other folder that is on the MATLAB path.
Use this table as a general guide when creating and saving your files:
| If your program or routine . . . | then . . . |
|---|---|
| Requires only one function | Make it a single (primary) function in the file. |
| Also requires subroutines | Make each subroutine a subfunction within same 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 file in a MATLAB class folder. |
| Is to have limited access | Put the file in a private subfolder. |
| Is part of a group of similar functions or classes | Put the file in a package subfolder. |
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 program 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 program 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 program 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 Functions in Files | Base and Function Workspaces | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |