Support Variable Number of Inputs
This example shows how to define a function that accepts a variable number of input arguments usingvarargin
. Thevarargin
argument is a cell array that contains the function inputs, where each input is in its own cell.
Create a function in a file namedplotWithTitle.m
that accepts a variable number of paired (x,y) inputs for theplot
function and an optional title. If the function receives an odd number of inputs, it assumes that the last input is a title.
functionplotWithTitle(varargin)ifrem(nargin,2) ~= 0 myTitle = varargin{nargin}; numPlotInputs = nargin - 1;elsemyTitle ='Default Title'; numPlotInputs = nargin;endplot(varargin{1:numPlotInputs}) title(myTitle)
Becausevarargin
is a cell array, you access the contents of each cell using curly braces,{}
. The syntax变长度输入宗量{1:numPlotInputs}
creates a comma-separated list of inputs to theplot
function.
CallplotWithTitle
with two sets of (x,y) inputs and a title.
x = [1:.1:10]; y1 = sin(x); y2 = cos(x); plotWithTitle(x,y1,x,y2,'Sine and Cosine')
You can usevarargin
alone in an input argument list, or at the end of the list of inputs, such as
functionmyfunction(a,b,varargin)
In this case,varargin{1}
corresponds to the third input passed to the function, andnargin
returnslength(varargin) + 2
.