varargin – Matlab

A very important feature in coding languages is the power to be able to pass variable number of input arguments (and output arguments) to functions.

Yes, as expected, Matlab allows for that in a very simple way. In C, one uses the argc and argv parameters in the main and then has to deal with complicated pointers. Matlab uses a varargin and nargin which basically stands for variable arguments in and number of arguments in.

So here’s how its actually used. The best way to illustrate would be by giving an example of a function.

function sg(x,varargin)
% x is the data
% The expected varargin consist of windowsize, hopsize

defwindowsize = 512;
defhopsize = 256;

if nargin>=2
windowsize = varargin{1};
if nargin>=3
hopsize = varargin{2};
else
hopsize = windowsize/2;
end
else
windowsize = defwindowsize;
hopsize = defhopsize;
end

fprintf('WindowSize: %d\n',windowsize);
fprintf('HopSize: %d\n',hopsize);
% Do further processing...
end

This is an over-explained example, wherein we basically have the variable input arguments as the window size and the hop size (doesn’t matter what they are in the real application). x is a data component which is a compulsory argument. We have defaults set for the window size and hop size as 512 and 256 respectively.

In the initial part, we basically check what are the no. of received arguments (nargin), and appropriately assign the variables their values from varargin. Note that varargin is a cell array. For now, its important to note that the cell arrays are indexed with curly braces { }. More on the data-type cell arrays at a later point of time.

If the user does not specify the arguments or specifies only some of them, default values are picked and used. Note that if window size is defined by user, we select the hop size to be half of that window size and do not pick the default. (This is a little into signal processing.) The point is that you can also assign processed values.

It would be incomplete to talk of variable input arguments without having a check on whether the number of input arguments are appropriate. This is done by using

error(nargchk(lowvalue,highvalue,nargin));

inside the code of the body. Try it out in the above function.

Similarly one can use variable number of output arguments by using varargout and nargout.

On writing such functions, it becomes easier for users, with little knowledge of details and arguments to just try out the functions and see what outputs are produced.

Advertisements

5 thoughts on “varargin – Matlab

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s