Next: , Previous: , Up: Functions and Scripts   [Contents][Index]


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. See Cell Array Objects.

Function File: nthargout (n, func, …)
Function File: 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, nargout, varargin, varargout, isargout.

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.

Built-in Function: nargout ()
Built-in Function: 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")

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, varargout, isargout, nthargout.

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.

Function File: 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, error, nargout, nargin.

Function File: nargoutchk (minargs, maxargs)
Function File: msgstr = nargoutchk (minargs, maxargs, nargs)
Function File: msgstr = nargoutchk (minargs, maxargs, nargs, "string")
Function File: 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, error, nargout, nargin.

Besides the number of arguments, inputs can be checked for various properties. validatestring is used for string arguments and validateattributes for numeric arguments.

Function File: validstr = validatestring (str, strarray)
Function File: validstr = validatestring (str, strarray, funcname)
Function File: validstr = validatestring (str, strarray, funcname, varname)
Function File: 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, strcmpi, validateattributes, inputParser.

Function File: validateattributes (A, classes, attributes)
Function File: validateattributes (A, classes, attributes, arg_idx)
Function File: validateattributes (A, classes, attributes, func_name)
Function File: validateattributes (A, classes, attributes, func_name, arg_name)
Function File: 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.

"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.

"non-negative"

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).

See also: isa, validatestring, inputParser.

If none of the preceding functions is sufficient there is also the class inputParser which can perform extremely complex input checking for functions.

Function File: 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 addParamValue);
  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.

Accessor method: inputParser.Parameters

Return list of parameter names already defined.

Accessor method: inputParser.Results

Return structure with argument names as fieldnames and corresponding values.

Accessor method: inputParser.Unmatched

Return structure similar to Results, but for unmatched parameters. See the KeepUnmatched property.

Accessor method: inputParser.UsingDefaults

Return cell array with the names of arguments that are using default values.

Class property: inputParser.CaseSensitive = boolean

Set whether matching of argument names should be case sensitive. Defaults to false.

Class property: inputParser.FunctionName = name

Set function name to be used in error messages; Defaults to empty string.

Class property: 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 ParamValue 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 ParamValue type and it is expected to be followed by a value.

Class property: inputParser.StructExpand = boolean

Set whether a structure can be passed to the function instead of parameter/value pairs. Defaults to true. Not implemented yet.

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 "ParamValue"
  val_type = @(x) any (strcmp (x, {"linear", "quadratic"}));
  p.addParamValue ("type", "linear", val_type);
  val_verb = @(x) any (strcmp (x, {"low", "medium", "high"}));
  p.addParamValue ("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 ParamValue 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 ParamValue and Switch arguments may be mixed together and they must appear at the end.

Note 2: If both Optional and ParamValue 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 ParamValue or Switch arguments.

See also: nargin, validateattributes, validatestring, varargin.


Next: , Previous: , Up: Functions and Scripts   [Contents][Index]