nargoutchk

Validate number of output arguments

Syntax

nargoutchk(minargs, maxargs)

Description

nargoutchk(minargs, maxargs) throws an error if the number of outputs specified in the call is less than minargs or greater than maxargs. If the number of outputs is between minargs and maxargs (inclusive), nargoutchk does nothing.

When too few outputs are supplied, the identifier and message are:

identifier: 'MATLAB:nargoutchk:notEnoughOutputs'
       message: 'Not enough output arguments.'

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

identifier: 'MATLAB:nargoutchk:tooManyOutputs'
       message: 'Too many output arguments.'

Examples

This function uses nargoutchk to verify that a minimum of 2 and maximum of 5 input arguments are passed back to the calling function:

function [varargout] = check_outputs(array_in)
minargs=2;  maxargs=5;

% Number of outputs must be >=minargs and <=maxargs.
nargoutchk(minargs, maxargs)

for k=1:nargout
    varargout{k} = array_in(k)*3;
end

Initialize input array X to a vector of 6 elements:

X = 5:7:40
X =
     5    12    19    26    33    40

Call the example function with 1 output argument. This is less than the minimum (2) that was specified by nargoutchk and results in an error:

A = check_outputs(X);

Error using check_outputs
Not enough output arguments.

Call the function with 4 output arguments. This is within the allowable bounds (2 to 5) specified by nargoutchk:

[A, B, C, D] = check_outputs(X);

[A, B, C, D]
ans =
    15    36    57    78

Call the function with 6 output arguments. This exceeds the maximum (5) that was specified by nargoutchk and results in an error:

[A, B, C, D, E, F] = check_outputs(X);

Error using check_outputs
Too many output arguments.

More About

expand all

Tips

  • To verify that there are a minimum of N arguments, specify inf as maxargs. For example: nargoutchk(5,inf) throws an error when there are not at least five outputs.

Was this topic helpful?