TExcelTAD
Home › MATLAB / Octave › Calling Functions

Calling Functions

Almost everything you do in MATLAB is a function call: sqrt(x), size(A), plot(x, y). Functions take inputs in parentheses and can return one or more outputs. Understanding how multiple outputs work is one of the keys to reading MATLAB code.

Inputs

Inputs go in parentheses, separated by commas. Many functions accept optional inputs that change their behaviour:

matlab · try it yourself
v = [4 9 1 7];
disp(max(v))             % one input
disp(max(v, 5))          % compare each element with 5
disp(sort(v))            % ascending (default)
disp(sort(v, 'descend')) % an option given as text
disp(round(2.567 * 10) / 10)
9
   5   9   5   7
   1   4   7   9
   9   7   4   1
2.6000

Multiple outputs

Some functions can return several results. To receive them, put variable names in square brackets on the left of the =:

matlab · try it yourself
v = [4 9 1 7];
[biggest, where] = max(v);
fprintf('Max %d is at position %d\n', biggest, where);

[sorted, order] = sort(v);
disp(sorted)
disp(order)       % original positions of the sorted values

A = zeros(3, 5);
[nr, nc] = size(A);
fprintf('%d rows, %d columns\n', nr, nc);
Max 9 is at position 2
   1   4   7   9
   3   1   4   2
3 rows, 5 columns

The outputs are positional: the first name receives the first output and so on. If you ask for fewer outputs, you get only the first ones. A function can even behave differently depending on how many outputs you request, as size does: s = size(A) gives the vector [3 5], while [r, c] = size(A) splits it.

Ignoring outputs with ~

If you need only the second output, use a tilde ~ as a placeholder for the ones you don't want:

matlab · try it yourself
scores = [72 95 88 95 60];
[~, best] = max(scores);
fprintf('Best score belongs to student %d\n', best);
[~, ranking] = sort(scores, 'descend');
disp(ranking)
Best score belongs to student 2
   2   4   3   1   5

When there are ties, max returns the first position (student 2 rather than 4), and sort keeps tied elements in their original order.

Nesting calls

The output of one function can be the input of another. MATLAB evaluates from the inside out:

matlab · try it yourself
data = [3.2 -1.5 4.8 -0.3 2.1];
fprintf('%.2f\n', sqrt(sum(data .^ 2)));    % Euclidean norm
fprintf('%.2f\n', norm(data));              % the built-in does the same
fprintf('%d\n', numel(find(data < 0)));     % how many negatives
fprintf('%s\n', upper(strtrim('   done   ')));
6.33
6.33
2
DONE

Note: You can't index directly into a function's result in MATLAB: size(A)(1) is a syntax error (Octave allows it, but don't rely on it). Use size(A, 1) or store the result in a variable first.

Command syntax

Functions whose inputs are all text can be called without parentheses and quotes. These two lines are the same:

matlab
format long
format('long')

Command syntax is convenient at the prompt (clear all, hold on, axis equal), but can't return outputs and treats every word as text, so disp x prints the letter x, not the value of x.

Calling a function by name

feval calls a function whose name (or handle) is stored in a variable. This is handy when the function to use is chosen at run time:

matlab · try it yourself
names = {'min', 'max', 'mean', 'median'};
data = [5 3 9 1 7];
for k = 1:numel(names)
    fprintf('%-6s -> %g\n', names{k}, feval(names{k}, data));
end
min    -> 1
max    -> 9
mean   -> 5
median -> 5

Test yourself

How do you get both the minimum value and its index from v?

  1. min, idx = min(v)
  2. [m, idx] = min(v)
  3. (m, idx) = min(v)
  4. m = min(v, idx)

What does ~ mean in [~, k] = max(v)?

  1. Logical NOT
  2. Discard the first output
  3. Return the maximum negated
  4. Error

For A = ones(2, 7), what is s after s = size(A)?

  1. 2
  2. 7
  3. [2 7]
  4. 14