narginchk

Validate number of input arguments

Description

example

narginchk(minArgs,maxArgs)validates the number of input arguments in the call to the currently executing function.narginchkthrows an error if the number of inputs specified in the call is fewer thanminArgsor greater thanmaxArgs. If the number of inputs is betweenminArgsandmaxArgs(inclusive), thennarginchkdoes nothing.

Examples

collapse all

Verify that a function is called with a minimum of two and maximum of five input arguments.

In a file namedcheckInputs.m, create a function that usesnarginchkto verify that the function has been called with a valid number of inputs. The function signature indicates thatcheckInputsrequires two input arguments and accepts up to three additional, optional arguments.

functioncheckInputs(A,B,varargin) minArgs=2; maxArgs=5; narginchk(minArgs,maxArgs) fprintf('Received 2 required and %d optional inputs\n', length(varargin))end

Call the function with one input argument.

checkInputs(13)
Error using checkInputs (line 4) Not enough input arguments.

Call the function again with five input arguments.

checkInputs(13,7,42,1701,5)
Received 2 required and 3 optional inputs

Call the function again with six input arguments.

checkInputs(13,7,42,1701,5,88)
Error using checkInputs (line 4) Too many input arguments.

Input Arguments

collapse all

Minimum number of accepted inputs, specified as a scalar.

Data Types:single|double|int8|int16|int32|int64|uint8|uint16|uint32|uint64

Maximum number of accepted inputs, specified as a scalar.

Data Types:single|double|int8|int16|int32|int64|uint8|uint16|uint32|uint64

Tips

  • To verify that you have a minimum number of arguments, but no maximum number, setmaxArgstoinf. For example:narginchk(5,inf)throws an error when there are fewer than five inputs.

  • To verify that you have an exact number of arguments, specify the same value forminArgsandmaxArgs. For example:narginchk(3,3)throws an error if you do not have exactly three inputs.

    If you call a function with too few inputs, the message identifier and message are:

    标识符:“MATLAB: narginchk:notEnoughInputs' message: 'Not enough input arguments.'

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

    标识符:“MATLAB: narginchk:tooManyInputs' message: 'Too many input arguments.'

  • IfminArgsis 0 andmaxArgsisnargin(fun), then you do not need to usenarginchk.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Introduced in R2011b