Support Variable Number of Inputs

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

Create a function in a file named plotWithTitle.m that accepts a variable number of paired (x,y) inputs for the plot function and an optional title. If the function receives an odd number of inputs, it assumes that the last input is a title.

function plotWithTitle(varargin)
if rem(nargin,2) ~= 0
    myTitle = varargin{nargin};
    numPlotInputs = nargin - 1;
else
    myTitle = 'Default Title';
    numPlotInputs = nargin;
end

plot(varargin{1:numPlotInputs})
title(myTitle)

Because varargin is a cell array, you access the contents of each cell using curly braces, {}. The syntax varargin{1:numPlotInputs} creates a comma-separated list of inputs to the plot function.

Call plotWithTitle 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 use varargin alone in an input argument list, or at the end of the list of inputs, such as

function myfunction(a,b,varargin)

In this case, varargin{1} corresponds to the third input passed to the function, and nargin returns length(varargin) + 2.

See Also

|

Related Examples

More About

Was this topic helpful?