Flexible Arguments
Many built-in functions accept optional inputs (sort(v) or sort(v, 'descend')) and return a different number of outputs depending on the call. Your own functions can do the same with nargin, nargout, varargin and varargout.
| Name | Inside a function, it is… |
|---|---|
nargin |
The number of inputs the caller actually passed |
nargout |
The number of outputs the caller asked for |
varargin |
A cell array holding any extra inputs |
varargout |
A cell array you fill with extra outputs |
Optional inputs with nargin
Check nargin to give missing inputs a default value:
fprintf('%.2f\n', price_with_tax(100));
fprintf('%.2f\n', price_with_tax(100, 0.07));
fprintf('%.2f\n', price_with_tax(100, 0.07, 5));
function total = price_with_tax(net, rate, discount)
if nargin < 2
rate = 0.2; % default tax rate
end
if nargin < 3
discount = 0; % default: no discount
end
total = (net - discount) * (1 + rate);
end120.00
107.00
101.65
Calling with too many inputs is an error. Calling with too few is fine as long as the function doesn't use the missing ones.
Another common convention: the caller passes [] to mean "use the default" for a middle argument, and the function checks isempty:
fprintf('%.2f\n', price_with_tax(100, [], 10));
function total = price_with_tax(net, rate, discount)
if nargin < 2 || isempty(rate)
rate = 0.2;
end
if nargin < 3 || isempty(discount)
discount = 0;
end
total = (net - discount) * (1 + rate);
end108.00
Any number of inputs: varargin
Put varargin last in the input list to accept any number of extra arguments. Inside the function it is a cell array:
fprintf('%g\n', add_all(1, 2));
fprintf('%g\n', add_all(1, 2, 3, 4.5));
fprintf('%g\n', add_all());
function s = add_all(varargin)
s = 0;
for k = 1:numel(varargin)
s = s + varargin{k};
end
fprintf('(called with %d inputs) ', nargin);
end(called with 2 inputs) 3
(called with 4 inputs) 10.5
(called with 0 inputs) 0
Name-value options
The 'Name', value style used by plot and many other functions is built on varargin. A simple parser loops over the pairs:
greet('Ana');
greet('Ben', 'Greeting', 'Welcome');
greet('Cleo', 'Times', 2, 'Greeting', 'Hey');
function greet(name, varargin)
opts.Greeting = 'Hello'; % defaults
opts.Times = 1;
for k = 1:2:numel(varargin)
key = varargin{k};
if ~isfield(opts, key)
error('greet:badOption', 'Unknown option "%s"', key);
end
opts.(key) = varargin{k + 1};
end
for t = 1:opts.Times
fprintf('%s, %s!\n', opts.Greeting, name);
end
endHello, Ana!
Welcome, Ben!
Hey, Cleo!
Hey, Cleo!
For larger functions, MATLAB and Octave both provide inputParser, and modern MATLAB (R2019b+) has arguments blocks that declare types, sizes and defaults:
% MATLAB R2019b or later only (Octave parses but does not validate this)
function total = price_with_tax(net, rate, opts)
arguments
net (1,1) double {mustBeNonnegative}
rate (1,1) double = 0.2
opts.Discount (1,1) double = 0
end
total = (net - opts.Discount) * (1 + rate);
endDifferent outputs: nargout and varargout
nargout tells the function how many outputs the caller wants. Use it to skip expensive work or to change behaviour:
s = stats_of([4 8 15 16 23 42]);
fprintf('mean only: %.2f\n', s);
[m, sd, n] = stats_of([4 8 15 16 23 42]);
fprintf('mean %.2f, std %.2f, n %d\n', m, sd, n);
function [m, sd, n] = stats_of(v)
m = mean(v);
if nargout > 1
sd = std(v);
n = numel(v);
disp('(computed extra statistics)')
end
endmean only: 18.00
(computed extra statistics)
mean 18.00, std 13.49, n 6
varargout is the output counterpart of varargin: a cell array whose first nargout cells become the outputs:
[a, b, c] = split_digits(907);
fprintf('%d %d %d\n', a, b, c);
[x, y] = split_digits(56);
fprintf('%d %d\n', x, y);
function varargout = split_digits(n)
digits = num2str(n) - '0'; % char codes minus '0' gives the digit values
for k = 1:nargout
varargout{k} = digits(k);
end
end9 0 7
5 6
Validating inputs
Check inputs early and raise a clear error, rather than letting a confusing error appear deep inside the function. validateattributes and simple if tests both work:
try
circle_area(-2);
catch err
disp(err.message)
end
fprintf('%.4f\n', circle_area(1.5));
function A = circle_area(r)
if ~isnumeric(r) || any(r < 0)
error('circle:badRadius', 'Radius must be a non-negative number.');
end
A = pi * r.^2;
endRadius must be a non-negative number.
7.0686
Test yourself
Inside a function, what does nargin contain?
- The maximum number of inputs allowed
- The number of inputs actually passed by the caller
- The names of the inputs
- The number of outputs
What type is varargin inside the function?
- A numeric vector
- A struct
- A cell array
- A char array
Why check nargout inside a function?
- To validate inputs
- To compute only the outputs the caller requested
- To print the outputs
- It is required in every function