NARGINCHK in MATLAB

As discussed above, narginchk is used to validate the number of input arguments. We shall see an example where, if the input arguments in function calls are in range 2,10 then, the function prints them all else, narginchk throws an error.

Example 1:

Matlab




% MATLAB Code
fun(2,3,4)
fprintf("Lees input variables!\n\n")
fun()
  
% function
function fun(varargin)
    min = 2;
    max = 10;
    narginchk(min,max)
    disp(varargin)
end


Output:

 

In this code, the function fun takes a variable number of input arguments with the help of the varargin argument. Then, the narginchk function checks whether the number of passed input arguments is in the range 2,10 or not. If true then, the function displays the variable argument list.

As it can be seen in the output, the first function call with 3 (>2 & <10) arguments print the argument list however, the second function call throws an error as the number of arguments is 0.

How to Validate Number of Function Arguments in MATLAB?

MATLAB functions are generally defined input and output arguments. To validate the number of these input-output arguments, MATLAB provides us with the following functions:

  1. narginchk
  2. nargoutchk

Syntax:

narginchk(<minimum-inputs>, <maximum-inputs>)

nargoutchk(<minimum-outputs>, <maximum-outputs>)

We use narginchk and nargoutchk to manually handle the exceptions generated by a lesser or greater number of arguments during a function call. In the following sections, we will see the usage of both functions with examples.

Similar Reads

NARGINCHK in MATLAB

As discussed above, narginchk is used to validate the number of input arguments. We shall see an example where, if the input arguments in function calls are in range 2,10 then, the function prints them all else, narginchk throws an error....

NARGOUTCHK in MATLAB

...