nargchk

Validate number of input arguments

    Note:   nargchk will be removed in a future version. Use narginchk instead.

Syntax

msgstring = nargchk(minargs, maxargs, numargs)
msgstring = nargchk(minargs, maxargs, numargs, 'string')
msgstruct = nargchk(minargs, maxargs, numargs, 'struct')

Description

Use nargchk inside a function to check that the desired number of input arguments is specified in the call to that function.

msgstring = nargchk(minargs, maxargs, numargs) returns an error message string msgstring if the number of inputs specified in the call numargs is less than minargs or greater than maxargs. If numargs is between minargs and maxargs (inclusive), nargchk returns an empty matrix.

It is common to use the nargin function to determine the number of input arguments specified in the call.

msgstring = nargchk(minargs, maxargs, numargs, 'string') is essentially the same as the command shown above, as nargchk returns a string by default.

msgstruct = nargchk(minargs, maxargs, numargs, 'struct') returns an error message structure msgstruct instead of a string. The fields of the return structure contain the error message string and a message identifier. If numargs is between minargs and maxargs (inclusive), nargchk returns an empty structure.

When too few inputs are supplied, the message string and identifier are

       message: 'Not enough input arguments.'
    identifier: 'MATLAB:nargchk:notEnoughInputs'

When too many inputs are supplied, the message string and identifier are

       message: 'Too many input arguments.'
    identifier: 'MATLAB:nargchk:tooManyInputs'

Examples

Given the function CheckInputs,

function CheckInputs(x, y, z)
error(nargchk(2, 3, nargin))

Then typing CheckInputs(1) produces

Not enough input arguments.

More About

expand all

Tips

nargchk is often used together with the error function. The error function accepts either type of return value from nargchk: a message string or message structure. For example, this command provides the error function with a message string and identifier regarding which error was caught:

error(nargchk(2, 4, nargin, 'struct'))

If nargchk detects no error, it returns an empty string or structure. When nargchk is used with the error function, as shown here, this empty string or structure is passed as an input to error. When error receives an empty string or structure, it simply returns and no error is generated.

Was this topic helpful?