Writing Functions
A function definition has a fixed shape:
function [out1, out2] = functionName(in1, in2)
%FUNCTIONNAME One-line summary (the H1 help line).
% Longer description of inputs and outputs.
... statements that assign out1 and out2 ...
endfunctionkeyword, then the output list,=, the name and the input list.- Every output variable must be assigned before the function ends.
endcloses the function (required for local functions in scripts; good practice everywhere).
One input, one output
fprintf('%.1f\n', fahrenheit(37));
fprintf('%.1f ', fahrenheit([-40 0 100]));
fprintf('\n');
function f = fahrenheit(c)
%FAHRENHEIT Convert Celsius to Fahrenheit (works on arrays).
f = c * 9 / 5 + 32;
end98.6
-40.0 32.0 212.0
Because the body uses only element-wise operations, the function works on scalars and arrays alike. Writing functions that accept arrays is a good MATLAB habit.
Several inputs and outputs
List several outputs in square brackets. The caller decides how many to receive:
[area, perimeter] = rect_info(4, 2.5);
fprintf('area %.2f, perimeter %.2f\n', area, perimeter);
a = rect_info(3, 3); % only the first output
fprintf('area only: %g\n', a);
[~, p] = rect_info(1, 6); % only the second
fprintf('perimeter only: %g\n', p);
function [A, P] = rect_info(w, h)
A = w * h;
P = 2 * (w + h);
endarea 10.00, perimeter 13.00
area only: 9
perimeter only: 14
When the caller asks for one output, the function still computes both, but only A is returned. (Inside a function, nargout tells you how many outputs were requested, so you can skip expensive work; see the Flexible Arguments lesson.)
No outputs, no inputs
A function can have no outputs (drop the [...] = part) or no inputs (empty parentheses, or none):
print_banner('Results');
print_banner('Summary');
disp(default_tolerance())
function print_banner(heading)
border = repmat('=', 1, length(heading) + 4);
fprintf('%s\n| %s |\n%s\n', border, heading, border);
end
function tol = default_tolerance()
tol = 1e-6;
end===========
| Results |
===========
===========
| Summary |
===========
1.0000e-06
Returning early
return leaves the function immediately. Make sure all outputs have values before returning:
disp(first_negative([4 7 -2 5 -9]))
disp(first_negative([1 2 3]))
function idx = first_negative(v)
idx = 0; % default when nothing is found
for k = 1:numel(v)
if v(k) < 0
idx = k;
return
end
end
end3
0
Recursion
A function may call itself. Every recursive function needs a base case that stops the recursion:
fprintf('5! = %d\n', fact(5));
fprintf('gcd(84, 36) = %d\n', my_gcd(84, 36));
function r = fact(n)
if n <= 1
r = 1; % base case
else
r = n * fact(n - 1);
end
end
function g = my_gcd(a, b)
% Euclid's algorithm
if b == 0
g = a;
else
g = my_gcd(b, mod(a, b));
end
end5! = 120
gcd(84, 36) = 12
MATLAB limits recursion depth (500 by default in MATLAB, 256 in Octave), so for deep repetition prefer a loop.
Good habits
- Name functions with verbs or clear nouns:
compute_bmi,load_settings,rect_info. - Write the H1 help line and describe inputs and outputs.
- Avoid printing inside calculation functions; return values and let the caller decide what to print.
- Keep functions short and focused on one job.
- Make them work on arrays when it's natural.
Test yourself
What is wrong with function y = f(x) if the body never assigns y?
- Nothing
- Calling it and requesting the output raises an error
- y is automatically 0
- x is returned instead
How do you call [a, b] = g(x) but keep only b?
b = g(x)[~, b] = g(x)[b] = g(x, 2)g(x).b
What does every recursive function need?
- A global variable
- A base case that stops the recursion
- At least two outputs
- A while loop