| MATLAB® | ![]() |
| On this page… |
|---|
The MATLAB® software provides a full programming language that enables you to write a series of MATLAB statements into a file and then execute them with a single command. You write your program in an ordinary text file, giving the file a name of filename.m. The term you use for filename becomes the new command that MATLAB associates with the program. The file extension of .m makes this a MATLAB M-file.
M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output.
MATLAB scripts:
Are useful for automating a series of steps you need to perform many times.
Do not accept input arguments or return output arguments.
Store variables in a workspace that is shared with other scripts and with the MATLAB command line interface.
MATLAB functions:
Are useful for extending the MATLAB language for your application.
Can accept input arguments and return output arguments.
Store variables in a workspace internal to the function.
This simple function shows the basic parts of an M-file. Note that any line that begins with % is not executable:
function f = fact(n) Function definition line % Compute a factorial value. H1 line % FACT(N) returns the factorial of N, Help text % usually denoted by N! % Put simply, FACT(N) is PROD(1:N). Comment f = prod(1:n); Function body
The table below briefly describes each of these M-file parts. Both functions and scripts can have all of these parts, except for the function definition line which applies to functions only. These parts are described in greater detail following the table.
M-File Element | Description |
|---|---|
Function definition line | Defines the function name, and the number and order of input and output arguments |
A one line summary description of the program, displayed when you request help on an entire directory, or when you use lookfor | |
A more detailed description of the program, displayed together with the H1 line when you request help on a specific function | |
Program code that performs the actual computations and assigns values to any output arguments | |
Text in the body of the program that explains the internal workings of the program |
The function definition line informs MATLAB that the M-file contains a function, and specifies the argument calling sequence of the function. The function definition line for the fact function is

All MATLAB functions have a function definition line that follows this pattern.
Function Name. Function names must begin with a letter, may contain any alphanumeric characters or underscores, and must be no longer than the maximum allowed length (returned by the function namelengthmax). Because variables must obey similar rules, you can use the isvarname function to check whether a function name is valid:
isvarname myfun
Although function names can be of any length, MATLAB uses only the first N characters of the name (where N is the number returned by the function namelengthmax) and ignores the rest. Hence, it is important to make each function name unique in the first N characters:
N = namelengthmax
N =
63
Note Some operating systems may restrict file names to shorter lengths. |
The name of the text file that contains a MATLAB function consists of the function name with the extension .m appended. For example,
average.m
If the filename and the function definition line name are different, the internal (function) name is ignored. Thus, if average.m is the file that defines a function named computeAverage, you would invoke the function by typing
average
Note While the function name specified on the function definition line does not have to be the same as the filename, it is best to use the same name for both to avoid confusion. |
Function Arguments. If the function has multiple output values, enclose the output argument list in square brackets. Input arguments, if present, are enclosed in parentheses following the function name. Use commas to separate multiple input or output arguments. Here is the declaration for a function named sphere that has three inputs and three outputs:
function [x, y, z] = sphere(theta, phi, rho)
If there is no output, leave the output blank
function printresults(x)
or use empty square brackets:
function [] = printresults(x)
The variables that you pass to the function do not need to have the same name as those in the function definition line.
The H1 line, so named because it is the first help text line, is a comment line immediately following the function definition line. Because it consists of comment text, the H1 line begins with a percent sign, %. For the average function, the H1 line is
% AVERAGE Mean of vector elements.
This is the first line of text that appears when a user types help functionname at the MATLAB prompt. Further, the lookfor function searches on and displays only the H1 line. Because this line provides important summary information about the M-file, it is important to make it as descriptive as possible.
You can create online help for your M-files by entering help text on one or more consecutive comment lines at the start of your M-file program. MATLAB considers the first group of consecutive lines immediately following the H1 line that begin with % to be the online help text for the function. The first line without % as the left-most character ends the help.
The help text for the average function is
% AVERAGE(X), where X is a vector, is the mean of vector % elements. Nonvector input results in an error.
When you type help functionname at the command prompt, MATLAB displays the H1 line followed by the online help text for that function. The help system ignores any comment lines that appear after this help block.
Note Help text in an M-file can be viewed at the MATLAB command prompt only (using help functionname). You cannot display this text using the MATLAB Help browser. You can, however, use the Help browser to get help on MATLAB functions and also to read the documentation on any MathWorks™ products. |
The function body contains all the MATLAB code that performs computations and assigns values to output arguments. The statements in the function body can consist of function calls, programming constructs like flow control and interactive input/output, calculations, assignments, comments, and blank lines.
For example, the body of the average function contains a number of simple programming statements:
[m,n] = size(x);
if (~((m == 1) || (n == 1)) || (m == 1 && n == 1)) % Flow control
error('Input must be a vector') % Error message display
end
y = sum(x)/length(x); % Computation and assignment
As mentioned earlier, comment lines begin with a percent sign (%). Comment lines can appear anywhere in an M-file, and you can append comments to the end of a line of code. For example,
% Add up all the vector elements. y = sum(x) % Use the sum function.
In addition to comment lines, you can insert blank lines anywhere in an M-file. Blank lines are ignored. However, a blank line can indicate the end of the help text entry for an M-file.
Block Comments. To write comments that require more than one line, use the block comment operators, %{ and %}:
%{
This next block of code checks the number of inputs
passed in, makes sure that each input is a valid data
type, and then branches to start processing the data.
%}
Note The %{ and %} operators must appear alone on the lines that immediately precede and follow the block of help text. Do not include any other text on these lines. |
You create M-files using a text editor. MATLAB provides a built-in editor, but you can use any text editor you like. Once you have written and saved the M-file, you can run the program as you would any other MATLAB function or command.
The process looks like this:

M-files are ordinary text files that you create using a text editor. If you use the MATLAB Editor/Debugger, open a new file by selecting New > M-File from the File menu at the top of the MATLAB Command Window.
Another way to edit an M-file is from the MATLAB command line using the edit function. For example,
edit foo
opens the editor on the file foo.m. Omitting a filename opens the editor on an untitled file.
You can create the fact function shown in Basic Parts of an M-File by opening your text editor, entering the lines shown, and saving the text in a file called fact.m in your current directory.
Once you have created this file, here are some things you can:
List the names of the files in your current directory:
what
List the contents of M-file fact.m:
type fact
Call the fact function:
fact(5)
ans =
120
Save any M-files you create and any MathWorks supplied M-files that you edit in directories outside of the directory tree in which the MATLAB software is installed. If you keep your files in any of the installed directories, your files may be overwritten when you install a new version of MATLAB.
MATLAB installs its software into directories under matlabroot/toolbox. To see what matlabroot is on your system, type matlabroot at the MATLAB command prompt.
Also note that locations of files in the matlabroot/toolbox directory tree are loaded and cached in memory at the beginning of each MATLAB session to improve performance. If you save files to matlabroot/toolbox directories using an external editor, or if you add or remove files from these directories using file system operations, enter the commands clear functionname and rehash toolbox before you use the files in the current session.
For more information, see the rehash function reference page or the section Toolbox Path Caching in the Desktop Tools and Development Environment documentation.
You can provide user information for the programs you write by including a help text section at the beginning of your M-file. (See Help Text).
You can also make help entries for an entire directory by creating a file with the special name Contents.m that resides in the directory. This file must contain only comment lines; that is, every line must begin with a percent sign. MATLAB displays the lines in a Contents.m file whenever you type
help directoryname
Contents.m files are optional. You might have directories of your own with M-files that you don't necessarily want public. For this or other reasons, you might choose not to provide this type of help listing for these directories. If you have a directory that is on the path that does not have a Contents.m file, MATLAB displays "(No table of contents file)" for that directory in response to the help command. If you do not want to see this displayed, creating an empty Contents.m file will disable this message for that directory.
Also, if a directory does not contain a Contents.m file, typing
help directoryname
displays the first help line (the H1 line) for each M-file in the directory.
There is a tool in the Current Directory browser, called the Contents Report, that you can use to help create and validate your Contents.m files. See Contents Report in the MATLAB Desktop Tools and Development Environment documentation for more information.
You can save a preparsed version of a function or script, called P-code files, for later MATLAB sessions using the pcode function. For example,
pcode average
parses average.m and saves the resulting pseudocode to the file named average.p. This saves MATLAB from reparsing average.m the first time you call it in each session.
MATLAB is very fast at parsing so the pcode function rarely makes much of a speed difference.
One situation where pcode does provide a speed benefit is for large GUI applications. In this case, many M-files must be parsed before the application becomes visible.
You can also use pcode to hide algorithms you have created in your M-file, if you need to do this for proprietary reasons.
![]() | Program Development | M-File Scripts and Functions | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |