Skip to Main Content Skip to Search
Product Documentation

varargin - Variable-length input argument list

Syntax

varargin

Description

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.

Examples

Variable Number of Function Inputs

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);
   celldisp(varargin)

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} =
    3.1416

varargin and Declared Inputs

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})
   end

Call varlist2 with more than two inputs.

varlist2(10,20,30,40,50)
Total number of inputs = 5
Inputs in varargin(3):
   30
   40
   50

See Also

inputname | nargin | narginchk | nargout | nargoutchk | varargout

Related Examples

More About

  


Free MATLAB Interactive Kit

Explore how to use MATLAB to make advancements in engineering and science.


Download free kit

Trials Available

Try the latest version of MATLAB and other MathWorks products.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS