This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.


Validate number of input arguments

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


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


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

msgtext = nargchk(minargs, maxargs, numargs) returns an error message character vector msgtext 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.

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

msgstruct = nargchk(minargs, maxargs, numargs, 'struct') returns an error message structure msgstruct instead of a character vector. The fields of the return structure contain the error message 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 and identifier are

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

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

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


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

collapse all


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

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

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

Introduced before R2006a

Was this topic helpful?