Skip to Main Content Skip to Search
Product Documentation

Scripts and Functions

Scripts

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.

Functions

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.

Types of Functions

MATLAB provides the following types of functions. Each function type is described in more detail in a later section of this documentation:

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.

Organizing Your Functions

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 functionMake it a single (primary) function in the file.
Also requires subroutinesMake each subroutine a subfunction within same file as the primary.
Is for use only in the context of a certain functionNest it within the other function. Nested functions also offer wider access to variables within the function.
Is a constructor or method of a MATLAB classPut the file in a MATLAB class folder.
Is to have limited accessPut the file in a private subfolder.
Is part of a group of similar functions or classesPut 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.

Identifying Dependencies

If you need to know what other functions and scripts your program is dependent upon, use one of the techniques described below.

Simple Display of Program File Dependencies

For a simple display of all program files referenced by a particular function, follow these steps:

  1. Type clear functions to clear all functions from memory (see Note below).

      Note   clear functions does not clear functions locked by mlock. If you have locked functions (which you can check using inmem) unlock them with munlock, and then repeat step 1.

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

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

Detailed Display of Program File Dependencies

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


Recommended Products

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