octave: Multiple Return Values
11.3 Multiple Return Values
===========================
Unlike many other computer languages, Octave allows you to define
functions that return more than one value. The syntax for defining
functions that return multiple values is
function [RET-LIST] = NAME (ARG-LIST)
BODY
endfunction
where NAME, ARG-LIST, and BODY have the same meaning as before, and
RET-LIST is a comma-separated list of variable names that will hold the
values returned from the function. The list of return values must have
at least one element. If RET-LIST has only one element, this form of
the ‘function’ statement is equivalent to the form described in the
previous section.
Here is an example of a function that returns two values, the maximum
element of a vector and the index of its first occurrence in the vector.
function [max, idx] = vmax (v)
idx = 1;
max = v (idx);
for i = 2:length (v)
if (v (i) > max)
max = v (i);
idx = i;
endif
endfor
endfunction
In this particular case, the two values could have been returned as
elements of a single array, but that is not always possible or
convenient. The values to be returned may not have compatible
dimensions, and it is often desirable to give the individual return
values distinct names.
It is possible to use the ‘nthargout’ function to obtain only some of
the return values or several at once in a cell array. Cell Array
Objects.
-- : nthargout (N, FUNC, ...)
-- : nthargout (N, NTOT, FUNC, ...)
Return the Nth output argument of the function specified by the
function handle or string FUNC.
Any additional arguments are passed directly to FUNC. The total
number of arguments to call FUNC with can be passed in NTOT; by
default NTOT is N. The input N can also be a vector of indices of
the output, in which case the output will be a cell array of the
requested output arguments.
The intended use ‘nthargout’ is to avoid intermediate variables.
For example, when finding the indices of the maximum entry of a
matrix, the following two compositions of nthargout
M = magic (5);
cell2mat (nthargout ([1, 2], @ind2sub, size (M),
nthargout (2, @max, M(:))))
⇒ 5 3
are completely equivalent to the following lines:
M = magic (5);
[~, idx] = max (M(:));
[i, j] = ind2sub (size (M), idx);
[i, j]
⇒ 5 3
It can also be helpful to have all output arguments in a single
cell in the following manner:
USV = nthargout ([1:3], @svd, hilb (5));
See also: nargin XREFnargin, nargout XREFnargout,
DONTPRINTYET varargin XREFvarargin, varargout XREFvarargout, *noteDONTPRINTYET varargin XREFvarargin, varargout XREFvarargout,
isargout XREFisargout.
In addition to setting ‘nargin’ each time a function is called,
Octave also automatically initializes ‘nargout’ to the number of values
that are expected to be returned. This allows you to write functions
that behave differently depending on the number of values that the user
of the function has requested. The implicit assignment to the built-in
variable ‘ans’ does not figure in the count of output arguments, so the
value of ‘nargout’ may be zero.
The ‘svd’ and ‘lu’ functions are examples of built-in functions that
behave differently depending on the value of ‘nargout’.
It is possible to write functions that only set some return values.
For example, calling the function
function [x, y, z] = f ()
x = 1;
z = 2;
endfunction
as
[a, b, c] = f ()
produces:
a = 1
b = [](0x0)
c = 2
along with a warning.
-- : nargout ()
-- : nargout (FCN)
Report the number of output arguments from a function.
Called from within a function, return the number of values the
caller expects to receive. At the top level, ‘nargout’ with no
argument is undefined and will produce an error.
If called with the optional argument FCN—a function name or
handle—return the number of declared output values that the
function can produce.
If the final output argument is VARARGOUT the returned value is
negative.
For example,
f ()
will cause ‘nargout’ to return 0 inside the function ‘f’ and
[s, t] = f ()
will cause ‘nargout’ to return 2 inside the function ‘f’.
In the second usage,
nargout (@histc) # or nargout ("histc") using a string input
will return 2, because ‘histc’ has two outputs, whereas
nargout (@imread)
will return -2, because ‘imread’ has two outputs and the second is
VARARGOUT.
Programming Note. ‘nargout’ does not work for built-in functions
and returns -1 for all anonymous functions.
See also: nargin XREFnargin, varargout XREFvarargout,
isargout XREFisargout, nthargout XREFnthargout.
It is good practice at the head of a function to verify that it has
been called correctly. In Octave the following idiom is seen frequently
if (nargin < min_#_inputs || nargin > max_#_inputs)
print_usage ();
endif
which stops the function execution and prints a message about the
correct way to call the function whenever the number of inputs is wrong.
For compatibility with MATLAB, ‘narginchk’ and ‘nargoutchk’ are
available which provide similar error checking.
-- : narginchk (MINARGS, MAXARGS)
Check for correct number of input arguments.
Generate an error message if the number of arguments in the calling
function is outside the range MINARGS and MAXARGS. Otherwise, do
nothing.
Both MINARGS and MAXARGS must be scalar numeric values. Zero, Inf,
and negative values are all allowed, and MINARGS and MAXARGS may be
equal.
Note that this function evaluates ‘nargin’ on the caller.
See also: nargoutchk XREFnargoutchk, error XREFerror,
nargout XREFnargout, nargin XREFnargin.
-- : nargoutchk (MINARGS, MAXARGS)
-- : MSGSTR = nargoutchk (MINARGS, MAXARGS, NARGS)
-- : MSGSTR = nargoutchk (MINARGS, MAXARGS, NARGS, "string")
-- : MSGSTRUCT = nargoutchk (MINARGS, MAXARGS, NARGS, "struct")
Check for correct number of output arguments.
In the first form, return an error if the number of arguments is
not between MINARGS and MAXARGS. Otherwise, do nothing. Note that
this function evaluates the value of ‘nargout’ on the caller so its
value must have not been tampered with.
Both MINARGS and MAXARGS must be numeric scalars. Zero, Inf, and
negative are all valid, and they can have the same value.
For backwards compatibility, the other forms return an appropriate
error message string (or structure) if the number of outputs
requested is invalid.
This is useful for checking to that the number of output arguments
supplied to a function is within an acceptable range.
See also: narginchk XREFnarginchk, error XREFerror,
nargout XREFnargout, nargin XREFnargin.
Besides the number of arguments, inputs can be checked for various
properties. ‘validatestring’ is used for string arguments and
‘validateattributes’ for numeric arguments.
-- : VALIDSTR = validatestring (STR, STRARRAY)
-- : VALIDSTR = validatestring (STR, STRARRAY, FUNCNAME)
-- : VALIDSTR = validatestring (STR, STRARRAY, FUNCNAME, VARNAME)
-- : VALIDSTR = validatestring (..., POSITION)
Verify that STR is an element, or substring of an element, in
STRARRAY.
When STR is a character string to be tested, and STRARRAY is a
cellstr of valid values, then VALIDSTR will be the validated form
of STR where validation is defined as STR being a member or
substring of VALIDSTR. This is useful for both verifying and
expanding short options, such as "r", to their longer forms, such
as "red". If STR is a substring of VALIDSTR, and there are
multiple matches, the shortest match will be returned if all
matches are substrings of each other. Otherwise, an error will be
raised because the expansion of STR is ambiguous. All comparisons
are case insensitive.
The additional inputs FUNCNAME, VARNAME, and POSITION are optional
and will make any generated validation error message more specific.
Examples:
validatestring ("r", {"red", "green", "blue"})
⇒ "red"
validatestring ("b", {"red", "green", "blue", "black"})
⇒ error: validatestring: multiple unique matches were found for 'b':
blue, black
See also: strcmp XREFstrcmp, strcmpi XREFstrcmpi,
DONTPRINTYET validateattributes XREFvalidateattributes, *noteDONTPRINTYET validateattributes XREFvalidateattributes,
inputParser XREFinputParser.
-- : validateattributes (A, CLASSES, ATTRIBUTES)
-- : validateattributes (A, CLASSES, ATTRIBUTES, ARG_IDX)
-- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME)
-- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME, ARG_NAME)
-- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME, ARG_NAME,
ARG_IDX)
Check validity of input argument.
Confirms that the argument A is valid by belonging to one of
CLASSES, and holding all of the ATTRIBUTES. If it does not, an
error is thrown, with a message formatted accordingly. The error
message can be made further complete by the function name FUN_NAME,
the argument name ARG_NAME, and its position in the input ARG_IDX.
CLASSES must be a cell array of strings (an empty cell array is
allowed) with the name of classes (remember that a class name is
case sensitive). In addition to the class name, the following
categories names are also valid:
"float"
Floating point value comprising classes "double" and "single".
"integer"
Integer value comprising classes (u)int8, (u)int16, (u)int32,
(u)int64.
"numeric"
Numeric value comprising either a floating point or integer
value.
ATTRIBUTES must be a cell array with names of checks for A. Some
of them require an additional value to be supplied right after the
name (see details for each below).
"<="
All values are less than or equal to the following value in
ATTRIBUTES.
"<"
All values are less than the following value in ATTRIBUTES.
">="
All values are greater than or equal to the following value in
ATTRIBUTES.
">"
All values are greater than the following value in ATTRIBUTES.
"2d"
A 2-dimensional matrix. Note that vectors and empty matrices
have 2 dimensions, one of them being of length 1, or both
length 0.
"3d"
Has no more than 3 dimensions. A 2-dimensional matrix is a
3-D matrix whose 3rd dimension is of length 1.
"binary"
All values are either 1 or 0.
"column"
Values are arranged in a single column.
"decreasing"
No value is NAN, and each is less than the preceding one.
"diag"
Value is a diagonal matrix.
"even"
All values are even numbers.
"finite"
All values are finite.
"increasing"
No value is NAN, and each is greater than the preceding one.
"integer"
All values are integer. This is different than using
‘isinteger’ which only checks its an integer type. This
checks that each value in A is an integer value, i.e., it has
no decimal part.
"ncols"
Has exactly as many columns as the next value in ATTRIBUTES.
"ndims"
Has exactly as many dimensions as the next value in
ATTRIBUTES.
"nondecreasing"
No value is NAN, and each is greater than or equal to the
preceding one.
"nonempty"
It is not empty.
"nonincreasing"
No value is NAN, and each is less than or equal to the
preceding one.
"nonnan"
No value is a ‘NaN’.
"nonnegative"
All values are non negative.
"nonsparse"
It is not a sparse matrix.
"nonzero"
No value is zero.
"nrows"
Has exactly as many rows as the next value in ATTRIBUTES.
"numel"
Has exactly as many elements as the next value in ATTRIBUTES.
"odd"
All values are odd numbers.
"positive"
All values are positive.
"real"
It is a non-complex matrix.
"row"
Values are arranged in a single row.
"scalar"
It is a scalar.
"size"
Its size has length equal to the values of the next in
ATTRIBUTES. The next value must is an array with the length
for each dimension. To ignore the check for a certain
dimension, the value of ‘NaN’ can be used.
"square"
Is a square matrix.
"vector"
Values are arranged in a single vector (column or vector).
DONTPRINTYET See also: isa XREFisa, *notevalidatestring:
DONTPRINTYET See also: isa XREFisa, validatestring
XREFvalidatestring, inputParser XREFinputParser.
If none of the preceding functions is sufficient there is also the
class ‘inputParser’ which can perform extremely complex input checking
for functions.
-- : P = inputParser ()
Create object P of the inputParser class.
This class is designed to allow easy parsing of function arguments.
The class supports four types of arguments:
1. mandatory (see ‘addRequired’);
2. optional (see ‘addOptional’);
3. named (see ‘addParameter’);
4. switch (see ‘addSwitch’).
After defining the function API with these methods, the supplied
arguments can be parsed with the ‘parse’ method and the parsing
results accessed with the ‘Results’ accessor.
-- : inputParser.Parameters
Return list of parameter names already defined.
-- : inputParser.Results
Return structure with argument names as fieldnames and
corresponding values.
-- : inputParser.Unmatched
Return structure similar to ‘Results’, but for unmatched
parameters. See the ‘KeepUnmatched’ property.
-- : inputParser.UsingDefaults
Return cell array with the names of arguments that are using
default values.
-- : inputParser.CaseSensitive = BOOLEAN
Set whether matching of argument names should be case sensitive.
Defaults to false.
-- : inputParser.FunctionName = NAME
Set function name to be used in error messages; Defaults to empty
string.
-- : inputParser.KeepUnmatched = BOOLEAN
Set whether an error should be given for non-defined arguments.
Defaults to false. If set to true, the extra arguments can be
accessed through ‘Unmatched’ after the ‘parse’ method. Note that
since ‘Switch’ and ‘Parameter’ arguments can be mixed, it is not
possible to know the unmatched type. If argument is found
unmatched it is assumed to be of the ‘Parameter’ type and it is
expected to be followed by a value.
-- : inputParser.StructExpand = BOOLEAN
Set whether a structure can be passed to the function instead of
parameter/value pairs. Defaults to true.
The following example shows how to use this class:
function check (varargin)
p = inputParser (); # create object
p.FunctionName = "check"; # set function name
p.addRequired ("pack", @ischar); # mandatory argument
p.addOptional ("path", pwd(), @ischar); # optional argument
## create a function handle to anonymous functions for validators
val_mat = @(x) isvector (x) && all (x <= 1) && all (x >= 0);
p.addOptional ("mat", [0 0], val_mat);
## create two arguments of type "Parameter"
val_type = @(x) any (strcmp (x, {"linear", "quadratic"}));
p.addParameter ("type", "linear", val_type);
val_verb = @(x) any (strcmp (x, {"low", "medium", "high"}));
p.addParameter ("tolerance", "low", val_verb);
## create a switch type of argument
p.addSwitch ("verbose");
p.parse (varargin{:}); # Run created parser on inputs
## the rest of the function can access inputs by using p.Results.
## for example, get the tolerance input with p.Results.tolerance
endfunction
check ("mech"); # valid, use defaults for other arguments
check (); # error, one argument is mandatory
check (1); # error, since ! ischar
check ("mech", "~/dev"); # valid, use defaults for other arguments
check ("mech", "~/dev", [0 1 0 0], "type", "linear"); # valid
## following is also valid. Note how the Switch argument type can
## be mixed into or before the Parameter argument type (but it
## must still appear after any Optional argument).
check ("mech", "~/dev", [0 1 0 0], "verbose", "tolerance", "high");
## following returns an error since not all optional arguments,
## `path' and `mat', were given before the named argument `type'.
check ("mech", "~/dev", "type", "linear");
_Note 1_: A function can have any mixture of the four API types but
they must appear in a specific order. ‘Required’ arguments must be
first and can be followed by any ‘Optional’ arguments. Only the
‘Parameter’ and ‘Switch’ arguments may be mixed together and they
must appear at the end.
_Note 2_: If both ‘Optional’ and ‘Parameter’ arguments are mixed in
a function API then once a string Optional argument fails to
validate it will be considered the end of the ‘Optional’ arguments.
The remaining arguments will be compared against any ‘Parameter’ or
‘Switch’ arguments.
DONTPRINTYET See also: nargin XREFnargin, *notevalidateattributes:
DONTPRINTYET See also: nargin XREFnargin, validateattributes
XREFvalidateattributes, validatestring XREFvalidatestring,
varargin XREFvarargin.