11.9.1 Validating the number of Arguments

In Octave the following idiom is seen frequently at the beginning of a function definition:

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.

Similar error checking is provided by narginchk and nargoutchk.

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

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

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Validating-the-number-of-Arguments.html