TExcelTAD
Home › MATLAB / Octave › Writing Functions

Writing Functions

A function definition has a fixed shape:

matlab
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 ...
end
  • function keyword, then the output list, =, the name and the input list.
  • Every output variable must be assigned before the function ends.
  • end closes the function (required for local functions in scripts; good practice everywhere).

One input, one output

matlab · try it yourself
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;
end
98.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:

matlab · try it yourself
[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);
end
area 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):

matlab · try it yourself
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:

matlab · try it yourself
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
end
3
0

Recursion

A function may call itself. Every recursive function needs a base case that stops the recursion:

matlab · try it yourself
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
end
5! = 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?

  1. Nothing
  2. Calling it and requesting the output raises an error
  3. y is automatically 0
  4. x is returned instead

How do you call [a, b] = g(x) but keep only b?

  1. b = g(x)
  2. [~, b] = g(x)
  3. [b] = g(x, 2)
  4. g(x).b

What does every recursive function need?

  1. A global variable
  2. A base case that stops the recursion
  3. At least two outputs
  4. A while loop