Main Content

Validate Number of Function Arguments

This example shows how to check whether your custom function receives a valid number of input or output arguments. MATLAB® performs some argument checks automatically. For other cases, you can use narginchk or nargoutchk.

Automatic Argument Checks

MATLAB checks whether your function receives more arguments than expected when it can determine the number from the function definition. For example, this function accepts up to two outputs and three inputs:

function [x,y] = myFunction(a,b,c)

If you pass too many inputs to myFunction, MATLAB issues an error. You do not need to call narginchk to check for this case.

[X,Y] = myFunction(1,2,3,4)
Error using myFunction
Too many input arguments.

Use the narginchk and nargoutchk functions to verify that your function receives:

  • A minimum number of required arguments.

  • No more than a maximum number of arguments, when your function uses varargin or varargout.

Input Checks with narginchk

Define a function in a file named testValues.m that requires at least two inputs. The first input is a threshold value to compare against the other inputs.

function testValues(threshold,varargin)
minInputs = 2;
maxInputs = Inf;
narginchk(minInputs,maxInputs)

for k = 1:(nargin-1)
   if (varargin{k} > threshold)
      fprintf('Test value %d exceeds %d\n',k,threshold);
   end
end

Call testValues with too few inputs.

testValues(10)
Error using testValues (line 4)
Not enough input arguments.

Call testValues with enough inputs.

testValues(10,1,11,111)
Test value 2 exceeds 10
Test value 3 exceeds 10

Output Checks with nargoutchk

Define a function in a file named mysize.m that returns the dimensions of the input array in a vector (from the size function), and optionally returns scalar values corresponding to the sizes of each dimension. Use nargoutchk to verify that the number of requested individual sizes does not exceed the number of available dimensions.

function [sizeVector,varargout] = mysize(x)
minOutputs = 0;
maxOutputs = ndims(x) + 1;
nargoutchk(minOutputs,maxOutputs)

sizeVector = size(x);

varargout = cell(1,nargout-1);
for k = 1:length(varargout)
   varargout{k} = sizeVector(k);
end

Call mysize with a valid number of outputs.

A = rand(3,4,2);
[fullsize,nrows,ncols,npages] = mysize(A)
fullsize =
     3     4     2

nrows =
     3

ncols =
     4

npages =
     2

Call mysize with too many outputs.

A = 1;
[fullsize,nrows,ncols,npages] = mysize(A)
Error using mysize (line 4)
Too many output arguments.

See Also

|

Related Topics