varargin - Variable length input argument list

Syntax

function y = bar(varargin)

Description

function y = bar(varargin) accepts a variable number of arguments into function bar.m.

The varargin statement is used only inside a function M-file to contain optional input arguments passed to the function. The varargin argument must be declared as the last input argument to a function, collecting all the inputs from that point onwards. In the declaration, varargin must be lowercase.

Examples

Example 1

Write an M-file function that displays the expected and optional arguments you pass to it

function vartest(argA, argB, varargin) 

optargin = size(varargin,2);
stdargin = nargin - optargin;

fprintf('Number of inputs = %d\n', nargin)

fprintf('  Inputs from individual arguments(%d):\n', ...
        stdargin)
if stdargin >= 1
    fprintf('     %d\n', argA)
end
if stdargin == 2
    fprintf('     %d\n', argB)
end

fprintf('  Inputs packaged in varargin(%d):\n', optargin)
 for k= 1 : size(varargin,2) 
     fprintf('     %d\n', varargin{k})
 end

Call this function and observe that the MATLAB software extracts those arguments that are not individually-specified from the varargin cell array:

vartest(10,20,30,40,50,60,70)
Number of inputs = 7
  Inputs from individual arguments(2):
     10
     20
  Inputs packaged in varargin(5):
     30
     40
     50
     60
     70

Example 2

The function

function myplot(x,varargin)
plot(x,varargin{:})

collects all the inputs starting with the second input into the variable varargin. myplot uses the comma-separated list syntax varargin{:} to pass the optional parameters to plot. The call

myplot(sin(0:.1:1),'color',[.5 .7 .3],'linestyle',':')

results in varargin being a 1-by-4 cell array containing the values 'color', [.5 .7 .3], 'linestyle', and ':'.

See Also

varargout, nargin, nargout, nargchk, nargoutchk, inputname

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS