This is machine translation

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

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.


Variable-length input argument list




varargin is an input variable in a function definition statement that allows the function to accept any number of input arguments. Specify varargin using lowercase characters, and include it as the last input argument after any explicitly declared inputs. When the function executes, varargin is a 1-by-N cell array, where N is the number of inputs that the function receives after the explicitly declared inputs. However, if the function receives no inputs after the explicitly declared inputs, varargin is an empty cell array.


collapse all

Define a function in a file named varlist.m that accepts a variable number of inputs and displays the values of each input.

function varlist(varargin)
   fprintf('Number of arguments: %d\n',nargin)

Call varlist with several inputs.

varlist(ones(3),'some text',pi)
Number of arguments: 3
varargin{1} =
     1     1     1
     1     1     1
     1     1     1

varargin{2} =
some text
varargin{3} =

Define a function in a file named varlist2.m that expects inputs X and Y, and accepts a variable number of additional inputs.

function varlist2(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})

Call varlist2 with more than two inputs.

Total number of inputs = 5
Inputs in varargin(3):

Introduced before R2006a

Was this topic helpful?