纪录片ntation

Support Variable Number of Inputs

This example shows how to define a function that accepts a variable number of input arguments usingvarargin. Thevararginargument is a cell array that contains the function inputs, where each input is in its own cell.

Create a function in a file namedplotWithTitle.mthat accepts a variable number of paired (x,y) inputs for theplotfunction 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)

Becausevararginis 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 theplotfunction.

CallplotWithTitlewith 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 usevararginalone 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, andnarginreturnslength(varargin) + 2.

See Also

|

Related Examples

More About

Was this topic helpful?