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 lowcase 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 explicity declared inputs.
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 tha expects inputs X and Y, and accepts a variable number of additional inputs.
function varlist2(X,Y,varargin)
fprintf('Total number of inputs= %d\',nargin)
nVarargs = length(varargin);
fprintf('Input 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