Functions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. The reference material consulted while preparing these pages is listed in the section bibliography. |
Written against MATLAB R2026b. The sessions below were run in GNU Octave 11.3.0 (MATLAB code that Octave also accepts) and show Octave’s output with blank lines omitted; the layout and the error texts that MATLAB prints differ, and the MATLAB wording is given only where it is stated as "not run here". The arguments block is only introduced here and is covered on Argument Validation.
A function takes inputs, returns outputs and keeps its variables to itself. It is the unit of reuse in MATLAB: scripts (see Scripts and Code Sections) run in an existing workspace and share its variables, functions run in their own. In the heatflow scenario every step of the simulation is a function: assemble the system, apply the boundary condition, relax the field, summarise the result.
Function files
A function stored in its own file is the standard form. The file plateStats.m below summarises a plate temperature field T.
function [tmax, tmin, tmean] = plateStats(T)
% PLATESTATS Summary statistics of a plate temperature field.
% [tmax, tmin, tmean] = plateStats(T) returns the maximum, minimum
% and mean of the finite entries of T.
vals = T(isfinite(T));
tmax = max(vals);
if nargout > 1
tmin = min(vals);
end
if nargout > 2
tmean = mean(vals);
end
end
Save it as plateStats.m in the current folder or in a folder on the search path (see Search Path, Startup and Files) and call it like any built-in function.
T = [20 25 30; 22 NaN 35; 21 24 33];
tmax = plateStats(T)
[tmax, tmin] = plateStats(T)
[~, ~, avg] = plateStats(T)
Octave 11.3.0 output:
tmax = 35
tmax = 35
tmin = 20
avg = 26.250
The definition line
The first executable line of every function is the definition line. It has these parts, in this order:
| Part | Rule |
|---|---|
|
The keyword, in lowercase. Required. |
Outputs |
Optional. One output needs no brackets ( |
Name |
Required. The same rules as for variable names: it starts with a letter and contains letters, digits and underscores. |
Inputs |
Optional. Names in parentheses, separated by commas. With no inputs the parentheses may be omitted ( |
|
Optional. Declarative checks of class, size and validators for inputs and outputs (R2019b for inputs; |
A function cannot be defined at the Command Window prompt. It lives in a file: a function file, or a script file that contains local functions (R2016b, anywhere in the script since R2024a; see Scripts and Code Sections).
The file name wins
MATLAB associates the program with the file name, not with the name on the definition line. If heatSum.m starts with function y = other(x), you call it with heatSum, and other is ignored. The documentation advises using the same name for the file and for the first function, and a script file cannot have the same name as a function defined in it. Because the file name is what counts, it follows the same naming rules as a variable.
The first function in a function file is the main function, the one visible to the command line and to other files. Functions that follow it are local functions, visible only inside the file (see Local, Nested and Private Functions).
The end statement
A function ends with an end, with the end of the file, or with the definition line of the next local function, whichever comes first. end is required when any function in the file contains a nested function, when the function is a local function in a script file, and, in a function file, when any local function in that file uses end. The documentation recommends it anyway for readability. Use end in every function and never mix the two styles in one file; the Code Analyzer (see Code Analyzer and Code Quality) reports many such problems before you run the code.
Inputs and outputs
-
Inputs are positional: the first value in the call goes to the first name, and so on. Trailing inputs may be left out, and a function that uses a missing one fails with an undefined-variable error when it reaches it. List required inputs first and optional ones after them.
-
Outputs are assigned by name: the function must assign each requested output before it ends. Calling
[tmax, tmin] = plateStats(T)requests two outputs; the function may not have assigned the third, and nothing is wrong because it was not requested. -
A function returns only what the caller asked for. Writing
plateStats(T)with no semicolon prints the first output asans; assigning nothing stores the first output inanswhen it exists. -
Names of outputs are not special:
tmaxin the function andtmaxin the caller are different variables that only happen to have the same name.
Multiple outputs
A function that returns several values lists them in brackets, and the caller receives them with the same shape of bracketed list. Requesting fewer outputs than the function defines is legal and takes the first ones. Requesting more is an error (see Errors raised at the call).
Output order is part of the interface. When a function has more outputs than most callers want, put the most used ones first, and let the function skip the expensive ones when nargout says they are not needed, as plateStats does above.
nargin and nargout
Inside a function, nargin is the number of inputs the caller passed and nargout is the number of outputs it requested. Both are available as plain names without calling anything. nargin(fname) and nargout(fname) with a function name or handle give the number of declared inputs or outputs of that function; a function that declares varargin or varargout reports a negative count (see Variable Number of Arguments).
function r = argCount(a, b, c)
r = [nargin nargout];
end
r = argCount(1)
r = argCount(1,2,3)
nargin("argCount"), nargout("argCount")
Octave 11.3.0 output:
r =
1 1
r =
3 1
ans = 3
ans = 1
Use nargin to supply defaults for trailing inputs, and nargout to avoid computing outputs nobody asked for. For optional or name-value inputs prefer an arguments block, which also documents the function (see Argument Validation). narginchk and nargoutchk check the counts; nargchk was removed.
Ignoring outputs and inputs with the tilde
To ignore an output the caller does not need, put the tilde operator in its place. It works in any position and any number of times, with consecutive tildes separated by commas, and it avoids creating a variable that would only waste memory.
[~, ~, avg] = plateStats(T)
Without the tilde you can only request the first N outputs. For example tmax = plateStats(T) keeps just the first output and ignores the rest.
The same operator works in a definition line for inputs that a function must accept but does not use. The typical case is a callback, which MATLAB calls with a fixed argument list (for example function onSlider(src, ~)). The tilde makes the intent clear and keeps the unused name out of the function workspace. A definition such as function f(myInput, ~, ~) is allowed.
Leaving early with return
return ends the function (or script) at once and gives control back to the caller. The outputs must already have been assigned. It is useful for guard clauses at the top, so the rest of the function is not nested one level deeper.
function k = firstAbove(T, tol)
k = 0;
if isempty(T)
return
end
for k = 1:numel(T)
if T(k) > tol
return
end
end
end
firstAbove([1 2 9 4], 5)
firstAbove([], 5)
firstAbove([1 2 3], 5)
Octave 11.3.0 output:
ans = 3
ans = 0
ans = 3
The last call shows a pitfall. When nothing is above the tolerance the loop finishes, and k keeps the last value of the loop variable (here 3), which looks like a hit at position 3. The loop variable survives the loop, so assign an explicit "not found" value after the loop, or use find(T > tol, 1), which returns an empty array when nothing matches. Details of break, continue and return are on Control Flow.
Source: MATLAB documentation: return
The function workspace
Each call of a function gets a fresh function workspace. It holds the inputs, the outputs and every variable the function creates, and it is separate from the base workspace and from the workspace of every other function, even local functions in the same file. When the function ends, the workspace is discarded; only the requested outputs survive.
-
A variable of the caller is invisible to the function unless it is passed as an input, and the other way round.
-
A script called from a function runs in that function’s workspace; a script called from the Command Window runs in the base workspace.
-
Nested functions are the exception: they share the variables of their parent function (see Local, Nested and Private Functions).
-
Data can also be shared through
globalandpersistentvariables, which break the isolation and are covered with the other scope tools on Workspaces, Scope, Global and Persistent.
Pass by value
Inputs behave as if they were copied: assigning to an input inside the function changes the function’s copy and never the caller’s variable. MATLAB avoids the real copy until the function writes to the input (copy on write), so passing a large array and only reading it costs no memory. The idiom T = process(T) therefore does not leave a stale T behind and does not copy twice.
function T = scaleField(T, factor)
T = T * factor;
tmp = 99;
end
T = [1 2 3]; tmp = 1;
S = scaleField(T, 10)
T
tmp
Octave 11.3.0 output:
S =
10 20 30
T =
1 2 3
tmp = 1
T and tmp in the base workspace did not change, although scaleField assigned both names. Handle objects (see Value and Handle Classes) are the exception: passing a handle copies the reference, so the function can modify the object it points to.
Types of functions
The documentation distinguishes these kinds of functions. Only the first is stored on its own; the others are defined next to code that uses them or without a file.
| Type | Where it lives | Visible to |
|---|---|---|
Main function (function file) |
A file named after the function |
The command line and other files, through the search path |
Local function |
After the main function in a function file, or in a script file |
Only the functions in the same file. It takes precedence over functions in other files with the same name. |
Nested function |
Completely inside another function in a program file ( |
The parent, siblings and nested levels as in the scope rules on Local, Nested and Private Functions. It reads and writes the variables of its parents. |
Private function |
A file in a subfolder named |
The functions and scripts in the folder immediately above |
Anonymous function |
An expression in a variable, |
Wherever the handle is passed. See Anonymous Functions and Function Handles. |
Method of a class |
Inside a |
Through objects of the class. See Properties and Methods. |
How MATLAB chooses among functions of the same name (variables first, then nested, local, private, class and path functions) is the subject of Function Precedence and Name Resolution. Since R2019b a name that is used as a variable anywhere in a function cannot also be called as a function in that function, which removes a class of surprising behaviour with variables created by eval or load.
Help text
The comment lines that follow the definition line (or, for a file, the first block of comments) are the function’s help text. help plateStats prints them, and the Live Editor and the function hints use them. Octave 11.3.0 shows the same lines for the plateStats file above:
'plateStats' is a function from the file /work/plateStats.m
PLATESTATS Summary statistics of a plate temperature field.
[tmax, tmin, tmean] = plateStats(T) returns the maximum, minimum
and mean of the finite entries of T.
The first line is the H1 line, which lookfor searches, so make it a one-line summary starting with the function name. The conventions for help text, help on local and private functions and the Live Editor format are on Help Text and Documenting Code; where to read help is on Getting Help and Documentation.
Errors raised at the call
The table lists the common errors of a function call. MATLAB raises them with these identifiers; the messages and identifiers are quoted from documentation and experience and are not run here (the wording varies by release; Octave prints its own texts, for example argCount: function called with too many inputs).
| Identifier | Message (MATLAB) | Cause |
|---|---|---|
|
Too many input arguments. |
The call passes more inputs than the definition line has names and no |
|
Too many output arguments. |
The call requests more outputs than the definition declares and no |
|
Not enough input arguments. |
The function reads an input that the call did not pass. |
|
Names the output argument (here |
A requested output was never assigned on the path the function took. |
|
Unrecognized function or variable 'x'. |
A name is neither a variable nor a function on the path, for example a misspelled function name or a variable that was never created. |
The unassigned-output case depends on the path through the function:
function out = maybeValue(flag)
if flag
out = 1;
end
end
a = maybeValue(true)
try, b = maybeValue(false), catch err, disp(err.message), end
Octave 11.3.0 output:
a = 1
value on right hand side of assignment is undefined
The first call works and the second fails because the if branch assigned nothing. Assign every output at the top of the function (even to [] or NaN) so that every path returns something. How to catch these errors is on Errors, Warnings and Exceptions.
Pitfalls
-
The file name and the function name differ. MATLAB calls the file name; the name on the definition line is ignored, and a reader looking for the function by name will not find it.
-
Forgetting to assign an output on one path, which raises the unassigned-output error at run time. The Code Analyzer reports many of these before you run the code.
-
Using
narginto guess defaults for many optional inputs produces longifchains. Use anargumentsblock, or name-value arguments. -
Reading the loop variable after a loop that found nothing (see
firstAboveabove). -
Shadowing a function with a variable. Assigning
max = 3hides themaxfunction in that workspace; clear the variable or rename it. Since R2019b this also applies inside a function if a name is used both as a variable and as a function. -
Changing the current folder and losing the function. A function file must be in the current folder or on the path (see Search Path, Startup and Files). An unsaved edit in the Editor is not the function that MATLAB calls.
-
Expecting a function to modify its input in place. Return the new value and assign it in the caller, unless the argument is a handle object.
-
Calling a function with the same name as a script or a variable that comes earlier in the lookup order.
-
iandjas loop variables hide the imaginary unit in the same function workspace. -
Large numbers of outputs. More than three or four outputs usually mean the function returns a structure or a table instead.
Where older books differ
Older books define functions with the same definition line and the same nargin/nargout idioms, and those still work. Differences to be aware of:
-
They cover
nargchkfor argument counts; it has been removed, usenarginchk/nargoutchkor anargumentsblock (R2019b). -
They validate inputs by hand with
ifchains,isnumericanderror, or withinputParserandvalidateattributes; the declarativeargumentsblock is the current approach. -
They put helper functions in their own files or as subfunctions at the end of a function file. Local functions in scripts (R2016b, anywhere in the script since R2024a) were not possible when the books were written.
-
They use
narginto detect name-value pairs; theName=Valuecall syntax (R2021a) andargumentsblocks replace that.