From scripts to building blocks
A script is the quickest way to get an answer: type the steps into a file and run it. But scripts do not scale. All their variables live in one shared workspace, so a script can quietly depend on a variable left over from an earlier one, and the only way to reuse a computation is to copy and paste it. Once a calculation is worth doing twice, it deserves to be a function: a named piece of code with clear inputs and outputs and its own private variables.
MATLAB adds a second, lighter kind of function, the anonymous function, written in one line and passed around as a value. Numerical work is full of functions that take other functions as input: a root finder needs the function whose root it seeks, an integrator the function to integrate, an ODE solver the right-hand side of the equation. Function handles are how you hand them over, and you will use them in every remaining lesson.
This lesson also covers what happens when things go wrong (errors and how to catch them) and how to check that your functions do what they should (assertions and testing frameworks), which together make the difference between a script that worked once and code you can trust.
Functions, files and the path
Definition— Function
A function is declared with function [out1, out2] = name(in1, in2) and ends with end. It runs in its own workspace: it sees only its inputs and creates only local variables, and it returns whatever is in its output variables when it finishes. Comment lines immediately after the declaration are its help text, shown by help name.
Definition— Function file
The standard home of a function is a file of the same name: stats.m beginning with function [m, s] = stats(x). Any further functions in that file are local functions (also called subfunctions), visible only within it.
Definition— Path
When you call stats(x), MATLAB and Octave look for a variable called stats, then a local function, then a file stats.m in the current folder, then in each folder on the search path. addpath(folder) adds a folder; which stats shows which file would run.
Local functions in a script: the one real incompatibility
Since release R2016b, MATLAB lets a script contain local functions too, but they must come at the end of the file, after all the script code. Octave works the other way round. When a file starts with function, Octave treats it as a function file; so a script that defines functions must start with some other statement (by convention the do-nothing statement 1;), and each function must be defined before the line that first calls it, because Octave defines it when execution reaches it.
There is therefore no single layout that both programs accept. This course's runnable programs use Octave's layout: 1; first, then the functions, then the script code. To run one in MATLAB, delete 1; and move the functions to the end of the file. For code that must run in both, put each function in its own file; that is also what most projects do once they have more than a handful of functions.
Writing functions
1; % a statement first, so Octave treats this file as a script
function [m, s] = stats(x)
% STATS Mean and sample standard deviation of a vector.
m = mean(x);
s = std(x);
end
function y = clamp(x, lo, hi)
% CLAMP Limit values to the range [lo, hi], by default [0, 1].
if nargin < 2
lo = 0;
end
if nargin < 3
hi = 1;
end
y = min(max(x, lo), hi);
end
data = [2 4 4 4 5 5 7 9];
[m, s] = stats(data);
fprintf('mean %.2f, standard deviation %.4f\n', m, s);
onlyMean = stats(data);
fprintf('one output requested: %.2f\n', onlyMean);
disp(clamp([-0.5 0.3 1.7]))
disp(clamp([-0.5 0.3 1.7], -1))
disp(clamp(15, 0, 10))mean 5.00, standard deviation 2.1381
one output requested: 5.00
0 0.3000 1.0000
-0.5000 0.3000 1.0000
10- Multiple outputs are listed in brackets. The caller takes as many as it wants:
[m, s] = stats(data)gets both,stats(data)only the first. Inside a function,nargouttells you how many were requested, so an expensive second output can be skipped when nobody asked for it. - Optional inputs are handled with
nargin, the number of arguments actually passed. MATLAB has no default-value syntax in the function line, soif nargin < 2, lo = 0; endis the classic idiom. stdcomputes the sample standard deviation (dividing by n − 1);std(x, 1)divides by n, giving 2 for this data. Knowing which one a function computes matters in statistics.clampis vectorised for free:minandmaxwork element-wise, so it clamps a whole array.
For functions that take any number of arguments, varargin collects extra inputs into a cell array and varargout returns a variable number of outputs. Larger functions often take name-value pairs, as in plot(x, y, 'LineWidth', 2); the inputParser class, available in both programs, parses and validates them. Recent MATLAB versions also offer arguments blocks for declaring types, sizes and defaults of inputs; Octave 11 reads such blocks but does not yet apply their validation (it warns that results may be incorrect), so avoid them in shared code for now.
Anonymous functions and function handles
Definition— Function handle
A function handle is a value that refers to a function. @sin is a handle to a named function; @(x) x.^2 - 2 creates an anonymous function, a one-expression function without a file. Call either with parentheses, store it in a variable, or pass it to another function.
f = @(x) x.^2 - 2;
disp(f(3))
disp(f([1 2 3]))
g = @sin;
disp(g(pi / 2))
compose = @(outer, inner) @(x) outer(inner(x));
h = compose(@sqrt, @abs);
disp(h(-16))
rate = 0.05;
grow = @(p) p * (1 + rate);
rate = 0.50;
fprintf('%.2f\n', grow(100));
disp(arrayfun(@(n) sum(1:n), 1:5))
disp(func2str(f))
fprintf('root of f between 1 and 2: %.6f\n', fzero(f, [1 2]));7
-1 2 7
1
4
105.00
1 3 6 10 15
@(x) x .^ 2 - 2
root of f between 1 and 2: 1.414214- Write anonymous functions with element-wise operators (
.^,.*) so they work on arrays as well as scalars; solvers and plotting functions often call them with whole vectors. composereturns a new anonymous function: functions can build functions.- Captured values are snapshots.
growrefers torate, and the value 0.05 is copied into the handle when it is created. Changingrateafterwards does not affect it, sogrow(100)is 105, not 150. This is different from closures in JavaScript or Python, which see later changes. arrayfuncalls a function on each element and collects the results;cellfundoes the same for cell arrays (next lesson). They are convenient, but a true vectorised expression is usually faster.func2strshows a handle's source (Octave normalises the spacing; MATLAB shows it as typed), andfzerois the first of many functions that take a handle: it finds wherefcrosses zero, here √2.
Errors
error(identifier, format, values...) stops the function and raises an error. The identifier, two or more words separated by colons such as geometry:inequality, lets callers recognise the kind of error without parsing the message. try ... catch err ... end catches errors; err.identifier and err.message describe what happened.
1;
function area = triangleArea(a, b, c)
% TRIANGLEAREA Area from three side lengths (Heron's formula).
if any([a b c] <= 0)
error('geometry:nonPositive', 'side lengths must be positive, got %g, %g, %g', a, b, c);
end
if a + b <= c || a + c <= b || b + c <= a
error('geometry:inequality', 'sides %g, %g and %g cannot form a triangle', a, b, c);
end
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
end
sides = [3 4 5; 1 1 3; 2 -1 2; 5 5 6];
for k = 1:size(sides, 1)
t = sides(k, :);
try
fprintf('%g %g %g: area %.2f\n', t, triangleArea(t(1), t(2), t(3)));
catch err
switch err.identifier
case 'geometry:inequality'
fprintf('%g %g %g: skipped, %s\n', t, err.message);
otherwise
fprintf('%g %g %g: rejected (%s)\n', t, err.identifier);
end
end
end3 4 5: area 6.00
1 1 3: skipped, sides 1, 1 and 3 cannot form a triangle
2 -1 2: rejected (geometry:nonPositive)
5 5 6: area 12.00The function validates its inputs first and fails with a specific message, which is far more helpful than letting sqrt of a negative number quietly return a complex result. The caller decides what each kind of error means for it: here an impossible triangle is skipped with an explanation, and anything else is reported as rejected. When you catch an error you cannot handle, re-raise it with rethrow(err) rather than hiding it.
Two differences are worth knowing. In MATLAB the caught err is an MException object, and you can create one yourself with MException(...) and throw it; in Octave 11 the caught value is a struct with the same identifier, message and stack fields, and the MException function is not available, so stick to error, try and catch for portable code. And the identifiers of built-in errors differ: reading past the end of an array raises Octave:index-out-of-bounds in Octave and a MATLAB:... identifier in MATLAB. Dispatch only on identifiers you defined yourself.
Warnings (warning('id:x', 'message')) report a problem without stopping, and can be turned off by identifier. Numerical functions use them for situations like a nearly singular matrix (lesson 6).
Testing
The simplest check is assert(condition, message), which raises an error if the condition is false. A few lines of helper code go a long way:
1;
function tf = isLeapYear(y)
% ISLEAPYEAR True for leap years in the Gregorian calendar; works on arrays.
tf = (mod(y, 4) == 0 & mod(y, 100) ~= 0) | mod(y, 400) == 0;
end
function check(name, condition)
if condition
fprintf('PASS %s\n', name);
else
fprintf('FAIL %s\n', name);
end
end
check('2024 is a leap year', isLeapYear(2024));
check('1900 is not', ~isLeapYear(1900));
check('2000 is', isLeapYear(2000));
check('works element by element', isequal(isLeapYear([2023 2024 2100]), [false true false]));
check('97 leap years in every 400', nnz(isLeapYear(1:400)) == 97);
check('2100 is a leap year (deliberately wrong)', isLeapYear(2100));
assert(isLeapYear(2400), 'the 400-year rule failed');
disp('assertions passed')PASS 2024 is a leap year
PASS 1900 is not
PASS 2000 is
PASS works element by element
PASS 97 leap years in every 400
FAIL 2100 is a leap year (deliberately wrong)
assertions passedThe function uses the element-wise & and |, so it works on whole arrays, and one test checks a property over four centuries rather than a single example. The deliberately wrong test shows what a failure looks like.
Both programs have real testing frameworks, and they differ. Octave lets you write tests inside a function file, in comment blocks that start with %!, and runs them with test name:
function tf = isLeapYear(y)
tf = (mod(y, 4) == 0 & mod(y, 100) ~= 0) | mod(y, 400) == 0;
end
%!assert (isLeapYear (2024))
%!assert (~isLeapYear (1900))
%!test
%! years = 1:400;
%! assert (nnz (isLeapYear (years)), 97)
%!error isLeapYear ()Octave's assert also accepts an expected value and a tolerance, assert(observed, expected, tol), which is handy for numerical results; MATLAB's assert takes only a condition and a message. MATLAB has a unit-testing framework: script-based tests (sections of a script, each a test, run with runtests) and class-based tests that subclass matlab.unittest.TestCase and use qualifications such as verifyEqual(testCase, actual, expected, 'AbsTol', 1e-10). Teams run these in continuous integration, often with code-coverage reports.
How projects are organised and debugged
Research groups and engineering teams that live in MATLAB settle into similar habits.
One function per file, in a few folders. A typical project has a top-level script or two that drive an analysis (load data, call functions, save results), and folders of function files that do the work. A private subfolder holds helpers that only the functions in its parent folder can call. MATLAB's package folders, whose names start with + (such as +geometry/triangleArea.m, called as geometry.triangleArea), give functions a namespace so that two projects' helper.m files do not collide; Octave supports them as well. Paths are set once, at the top of the driver script or in a start-up file, rather than with cd scattered through the code.
Help text that help and lookfor can find. The first comment line after the function declaration, conventionally the function name in capitals followed by a one-line summary (the H1 line), is what lookfor searches; the following lines describe inputs, outputs and an example.
Functions over scripts. Because a script shares the base workspace, its result can depend on whatever happened to be lying around from the previous run. Experienced users keep scripts short and call clear at the top of driver scripts, or convert them to functions, so that every run starts from the same state.
The debugger. Both programs let you set breakpoints in the editor or with dbstop in name at line, step through code, and inspect variables. dbstop if error is especially useful: it pauses at the line that fails, with all its variables available, instead of only printing a message. Inserting keyboard in the code pauses there too. For speed problems, tic/toc time a block and the profiler (profile on, then profile viewer in MATLAB or profshow in Octave) shows where time goes.
Common misconceptions
Misconception
"A function can see the variables of the script that called it." Each function has its own workspace. Pass what it needs as arguments. (Global variables exist, declared with global, but they make code hard to test and reason about; avoid them.)
Misconception
"An anonymous function sees the current value of the variables it mentions." It captures their values when it is created. To use a new value, create the handle again, or pass the value as an argument.
Misconception
"The file name does not matter, only the function line." For a function file, the file name is what MATLAB and Octave use to find the function. If area.m declares function a = triangle_area(...), you call it as area, and both programs will warn or complain about the mismatch. Keep them the same.
Misconception
"Catching every error makes a program robust." A catch that ignores the error turns a clear failure into a wrong answer later. Catch only what you can handle, check the identifier, and rethrow the rest.
Exercises
1. Scripts and functions
Warm-upComputationalWhat does this display?
k = 2;
scale = @(x) k * x;
k = 10;
disp(scale(3))
2. Scripts and functions
CoreComputationalWhat does this script display?
1;
function r = power2(x, n)
if nargin < 2
n = 2;
end
r = x ^ n;
end
disp(power2(3) + power2(2, 3))
3. Scripts and functions
CoreComputationalWhat does this print?
1;
function [lo, hi] = bounds2(x)
lo = min(x);
hi = max(x);
end
[a, b] = bounds2([4 9 1 7]);
c = bounds2([4 9 1 7]);
fprintf('%d %d %d\n', a, b, c);
4. Scripts and functions
Warm-upComputationalWhat numbers does disp(arrayfun(@(n) n^2, [1 2 3]) + 1) show? Write them separated by single spaces.
5. Scripts and functions
CoreComputationalWhat does this print?
try
error('shop:stock', 'only %d left of %s', 3, 'tea');
catch err
fprintf('%s | %s\n', err.identifier, err.message);
end
6. Scripts and functions
CoreHumanYou want a single Octave script file that defines a helper function area and then calls it. Which layout works in Octave?
7. Scripts and functions
StretchHumanWhy is it better for a caller to dispatch on err.identifier than on err.message?
Further reading and resources
- GNU Octave manual: Functions and Scripts
- GNU Octave manual: Script FilesIncludes how Octave decides whether a file is a script or a function file.
- GNU Octave manual: Anonymous Functions
- GNU Octave manual: Errors and Warnings
- GNU Octave manual: Test FunctionsOctave's built-in %!test blocks.
- MathWorks documentationSearch for "Local Functions in Scripts" and "Testing Frameworks" for MATLAB's versions.