This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Scripts and Functions


The MATLAB® product provides a powerful programming language, as well as an interactive computational environment. You can enter commands from the language one at a time at the MATLAB command line, or you can write a series of commands to a file that you then execute as you would any MATLAB function. Use the MATLAB Editor or any other text editor to create your own function files. Call these functions as you would any other MATLAB function or command.

There are two kinds of program files:

  • Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.

  • Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.

If you are a new MATLAB programmer, just create the program files that you want to try out in the current folder. As you develop more of your own files, you will want to organize them into other folders and personal toolboxes that you can add to your MATLAB search path.

If you duplicate function names, MATLAB executes the one that occurs first in the search path.

To view the contents of a program file, for example, myfunction.m, use

type myfunction


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:

% Investigate the rank of magic squares
r = zeros(1,32);
for n = 3:32
   r(n) = rank(magic(n));

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 are files that can accept input arguments and return output arguments. The names of the 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 file rank.m is available in the folder


You can see the file with

type rank

Here is the file:

function r = rank(A,tol)
%   RANK Matrix rank.
%   RANK(A) provides an estimate of the number of linearly
%   independent rows or columns of a matrix A.
%   RANK(A,tol) is the number of singular values of A
%   that are larger than tol.
%   RANK(A) uses the default tol = max(size(A)) * norm(A) * eps.

s = svd(A);
if nargin==1
   tol = max(size(A)') * max(s) * eps;
r = sum(s > tol);

The first line of a function 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

help rank

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

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:

r = rank(A)
r = rank(A,1.e-6)

Many functions 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 that 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.

Types of Functions

MATLAB offers several different types of functions to use in your programming.

Anonymous Functions

An anonymous function is a simple form of the MATLAB function that is defined within a single MATLAB statement. It consists of a single MATLAB expression and any number of input and output arguments. You can define an anonymous function right at the MATLAB command line, or within a function or script. This gives you a quick means of creating simple functions without having to create a file for them each time.

The syntax for creating an anonymous function from an expression is

f = @(arglist)expression

The statement below creates an anonymous function that finds the square of a number. When you call this function, MATLAB assigns the value you pass in to variable x, and then uses x in the equation x.^2:

sqr = @(x) x.^2;

To execute the sqr function defined above, type

a = sqr(5)
a =

Primary and Subfunctions

Any function that is not anonymous must be defined within a file. Each such function file contains a required primary function that appears first, and any number of subfunctions that can follow the primary. Primary functions have a wider scope than subfunctions. That is, primary functions can be called from outside of the file that defines them (for example, from the MATLAB command line or from functions in other files) while subfunctions cannot. Subfunctions are visible only to the primary function and other subfunctions within their own file.

The rank function shown in the section on Functions is an example of a primary function.

Private Functions

A private function is a type of primary function. Its unique characteristic is that it is visible only to a limited group of other functions. This type of function can be useful if you want to limit access to a function, or when you choose not to expose the implementation of a function.

Private functions reside in subfolders with the special name private. They are visible only to functions in the parent folder. For example, assume the folder newmath is on the MATLAB search path. A subfolder of newmath called private can contain functions that only the functions in newmath can call.

Because private functions are invisible outside the parent folder, they can use the same names as functions in other folders. This is useful if you want to create your own version of a particular function while retaining the original in another folder. Because MATLAB looks for private functions before standard functions, it will find a private function named test.m before a nonprivate file named test.m.

Nested Functions

You can define functions within the body of another function. These are said to be nested within the outer function. A nested function contains any or all of the components of any other function. In this example, function B is nested in function A:

function x = A(p1, p2)
   function y = B(p3)

Like other functions, a nested function has its own workspace where variables used by the function are stored. But it also has access to the workspaces of all functions in which it is nested. So, for example, a variable that has a value assigned to it by the primary function can be read or overwritten by a function nested at any level within the primary. Similarly, a variable that is assigned in a nested function can be read or overwritten by any of the functions containing that function.

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 a new function in a file called falling.m:

function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;

Then interactively enter the statements

global GRAVITY
y = falling((0:.1:5)');

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 vs. Function Syntax

You can write MATLAB functions that accept character arguments without the parentheses and quotes. That is, MATLAB interprets

foo a b c



However, when you use the unquoted command form, MATLAB cannot return output arguments. For example,

legend apples oranges

creates a legend on a plot using apples and oranges as labels. If you want the legend command to return its output arguments, then you must use the quoted form:

[legh,objh] = legend('apples','oranges');

In addition, you must use the quoted form if any of the arguments is not a character vector.


While the unquoted command syntax is convenient, in some cases it can be used incorrectly without causing MATLAB to generate an error.

Constructing Character Arguments in Code

The quoted function form enables you to construct character arguments within the code. 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, to build the file name:

for d = 1:31
   s = ['August' int2str(d) '.dat'];
   % Code to process the contents of the d-th file
Was this topic helpful?