Skip to Main Content Skip to Search
Product Documentation

Working with Functions in Files

Overview

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 program file.

Types of Program Files

Program 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:

MATLAB functions:

Basic Parts of a Program File

This simple function shows the basic parts of a program file. 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

This table briefly describes each of these program file parts. Both functions and scripts can have all of these parts, except for the function definition line which applies to functions only. The sections that follow the table describe these parts in greater detail.

File Element

Description

Function definition line
(functions only)

Defines the function name, and the number and order of input and output arguments

H1 line

A one line summary description of the program, displayed when you request help on an entire folder, or when you use lookfor

Help text

A more detailed description of the program, displayed together with the H1 line when you request help on a specific function

Function or script body

Program code that performs the actual computations and assigns values to any output arguments

Comments

Text in the body of the program that explains the internal workings of the program

Function Definition Line

The function definition line informs MATLAB that the file contains a function, and specifies the argument calling sequence of the function. This line contains the function keyword and must always be the first line of the file, except for lines that are nonexecutable comments. 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, can 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

Function names also cannot be the same as any MATLAB keyword. Use the iskeyword function with no inputs to display a list of all keywords.

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

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 file name and the function definition line name are different, MATLAB ignores the internal (function) name. Thus, if average.m is the file that defines a function named computeAverage, you would invoke the function by typing

average

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 the variables in the function definition line.

The H1 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 file, it is important to make it as descriptive as possible.

Help Text

You can create online help for your program files by entering help text on one or more consecutive comment lines at the start of your 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.

The Function or Script Body

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

Comments

As mentioned earlier, comment lines begin with a percent sign (%). Comment lines can appear anywhere in a program 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 the file. Blank lines are ignored. However, a blank line can indicate the end of the help text entry for a program 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.
%}

Creating a Program File

You create files for your programs 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 file, you can run the program as you would any other MATLAB function or command.

The process looks like this:

Using Text Editors

Program 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 > File from the File menu at the top of the MATLAB Command Window.

Another way to edit a program 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 file name opens the editor on an untitled file.

You can create the fact function shown in Basic Parts of a Program File by opening your text editor, entering the lines shown, and saving the text in a file called fact.m in your current folder.

Once you have created this file, here are some things you can:

A Word of Caution on Saving Program Files

Save any files you create and any MathWorks supplied files that you edit in folders outside of the folder tree in which the MATLAB software is installed. If you keep your files in any of the installed folders, your files can be overwritten when you install a new version of MATLAB.

MATLAB installs its software into folders 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 folder tree are loaded and cached in memory at the beginning of each MATLAB session to improve performance. If you save files to matlabroot/toolbox folders using an external editor, or if you add or remove files from these folders 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.

Providing Help for Your Program

You can provide user information for the programs you write by including a help text section at the beginning of your program file. (See Help Text).

You can also make help entries for an entire folder by creating a file with the special name Contents.m that resides in the folder. 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 foldername

Contents.m files are optional. If you have a folder that is on the path that does not contain a Contents.m file, MATLAB displays the first comment line (the "H1" line) of each .m file in response to typing help foldername. If you do not want to display any help summaries at all, create an empty an empty Contents.m file in that folder. When an empty Contents.m file exists, typing help foldername causes MATLAB to respond with No help found for foldername..

To get help in creating and validating your Contents.m files, you can use the Contents Report tool in the Current Folder browser. See Displaying and Updating a Report on the Contents of a Folder for more information.

Cleaning Up When the Function Completes

When you have programmed all that you set out to do in your file, there is one last step to consider before it is complete. Make sure that you leave your program environment in a clean state that does not interfere with any other program code. For example, you might want to

MATLAB provides the onCleanup function for this purpose. This function, when used within any program, establishes a cleanup routine for that function. When the function terminates, whether normally or in the event of an error or Ctrl+C, MATLAB automatically executes the cleanup routine.

The following statement establishes a cleanup routine cleanupFun for the currently running program:

cleanupObj = onCleanup(@cleanupFun);

When your program exits, MATLAB finds any instances of the onCleanup class and executes the associated function handles. The process of generating and activating function cleanup involves the following steps:

  1. Write one or more cleanup routines for the program under development. Assume for now that it takes only one such routine.

  2. Create a function handle for the cleanup routine.

  3. At some point, generally early in your program code, insert a call to the oncleanup function, passing the function handle.

  4. When the program is run, the call to onCleanup constructs a cleanup object that contains a handle to the cleanup routine created in step 1.

  5. When the program ends, MATLAB implicitly clears all objects that are local variables. This invokes the destructor method for each local object in your program, including the cleanup object constructed in step 4.

  6. The destructor method for this object invokes this routine if it exists. This perform the tasks needed to restore your programming environment.

You can declare any number of cleanup routines for a program file. Each call to onCleanup establishes a separate cleanup routine for each cleanup object returned.

If, for some reason, the object returned by onCleanup persists beyond the life of your program, then the cleanup routine associated with that object is not run when your function terminates. Instead, it will run whenever the object is destroyed (e.g., by clearing the object variable).

Your cleanup routine should never rely on variables that are defined outside of that routine. For example, the nested function shown here on the left executes with no error, whereas the very similar one on the right fails with the error, Undefined function or variable 'k'. This results from the cleanup routine's reliance on variable k which is defined outside of the nested cleanup routine:

function testCleanup               function testCleanup
k = 3;                             k = 3;
myFun                              obj = onCleanup(@myFun);
    function myFun                     function myFun
    fprintf('k is %d\n', k)            fprintf('k is %d\n', k)
    end                                end
end                                end

Examples of Cleaning Up a Program Upon Exit

Example 1 — Close Open Files on Exit.  MATLAB closes the file with identifier fid when function openFileSafely terminates:

function openFileSafely(fileName)
fid = fopen(fileName, 'r');
c = onCleanup(@()fclose(fid));

s = fread(fid);
     .
     .
     .
end

Example 2 — Maintain the Selected Folder.  This example preserves the current folder whether functionThatMayError returns an error or not:

function changeFolderSafely(fileName)
   currentFolder = pwd;
   c = onCleanup(@()cd(currentFolder));

   functionThatMayError;
   end   % c executes cd(currentFolder) here.

Example 3 — Close Figure and Restore MATLAB Path.  This example extends the MATLAB path to include files in the toolbox\images folders, and then displays a figure from one of these folders. After the figure displays, the cleanup routine restore_env closes the figure and restores the path to its original state:

function showImageOutsidePath(imageFile)
fig1 = figure;
imgpath = genpath([matlabroot '\toolbox\images']);

% Define the cleanup routine.
cleanupObj = onCleanup(@()restore_env(fig1, imgpath));

% Modify the path to gain access to the image file, 
% and display the image.
addpath(imgpath);
rgb = imread(imageFile);
fprintf('\n   Opening the figure %s\n', imageFile);
image(rgb);
pause(2);

   % This is the cleanup routine.
   function restore_env(fighandle, newpath)
   disp '   Closing the figure'
   close(fighandle);
   pause(2)
   
   disp '   Restoring the path'
   rmpath(newpath);
   end
end

Run the function as shown here. You can verify that the path has been restored by comparing the length of the path before and after running the function:

origLen = length(path);

showImageOutsidePath('greens.jpg')
   Opening the figure greens.jpg
   Closing the figure
   Restoring the path

currLen = length(path);
currLen == origLen
ans =
     1

Retrieving Information About the Cleanup Routine

In Example 3 shown above, the cleanup routine and data needed to call it are contained in a handle to an anonymous function:

@()restore_env(fig1, imgpath)

The details of that handle are then contained within the object returned by the onCleanup function:

cleanupObj = onCleanup(@()restore_env(fig1, imgpath));

You can access these details using the task property of the cleanup object as shown here. (Modify the showImageOutsidePath function by adding the following code just before the comment line that says, "% This is the cleanup routine.")

disp '   Displaying information from the function handle:'
task = cleanupObj.task;
fun = functions(task)
wsp = fun.workspace{2,1}
fprintf('\n');
pause(2);

Run the modified function to see the output of the functions command and the contents of one of the workspace cells:

showImageOutsidePath('greens.jpg')

Opening the figure greens.jpg
Displaying information from the function handle:
fun = 
     function: '@()restore_env(fig1,imgpath)'
         type: 'anonymous'
         file: 'c:\work\g6.m'
    workspace: {2x1 cell}
wsp = 
     imageFile: 'greens.jpg'
          fig1: 1
       imgpath: [1x3957 char]
    cleanupObj: [1x1 onCleanup]
           rgb: [300x500x3 uint8]
          task: @()restore_env(fig1,imgpath)

Closing the figure
Restoring the path

Using onCleanup Versus try-catch

Another way to run a cleanup routine when a function terminates unexpectedly is to use a try-catch statement. There are limitations to using this technique however. If the user ends the program by typing Ctrl+C, MATLAB immediately exits the try block, and the cleanup routine never executes. The cleanup routine also does not run when you exit the function normally.

The following program cleans up if an error occurs, but not in response to Ctrl+C:

function cleanupByCatch
try
    pause(10);
catch
    disp('   Collecting information about the error')
    disp('   Executing cleanup tasks')
end

Unlike the try-catch statement, the onCleanup function responds not only to a normal exit from your program and any error that might be thrown, but also to Ctrl+C. This next example replaces the try-catch with onCleanup:

function cleanupByFunc
obj = onCleanup(@()...
    disp('   Executing cleanup tasks'));
pause(10);

onCleanup in Scripts

onCleanup does not work in scripts as it does in functions. In functions, the cleanup object is stored in the function workspace. When the function exits, this workspace is cleared thus executing the associated cleanup routine. In scripts, the cleanup object is stored in the base workspace (that is, the workspace used in interactive work done at the command prompt). Because exiting a script has no effect on the base workspace, the cleanup object is not cleared and the routine associated with that object does not execute. To use this type of cleanup mechanism in a script, you would have to explicitly clear the object from the command line or another script when the first script terminates.

  


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