- publishing free software manuals
GNU Octave Manual Version 3
by John W. Eaton, David Bateman, Søren Hauberg
Paperback (6"x9"), 568 pages
ISBN 095461206X
RRP £24.95 ($39.95)

Get a printed copy>>>

11.3 Variable-length Argument Lists

Sometimes the number of input arguments is not known when the function is defined. As an example think of a function that returns the smallest of all its input arguments. For example,

a = smallest (1, 2, 3);
b = smallest (1, 2, 3, 4);

In this example both a and b would be 1. One way to write the smallest function is

function val = smallest (arg1, arg2, arg3, arg4, arg5)
  body
endfunction

and then use the value of nargin to determine which of the input arguments should be considered. The problem with this approach is that it can only handle a limited number of input arguments.

Octave supports the varargin keyword for handling a variable number of input arguments. Using varargin the function looks like this

function val = smallest (varargin)
  body
endfunction

In the function body the input arguments can be accessed through the variable varargin. This variable is a cell array containing all the input arguments. See section 6.2 Cell Arrays, for details on working with cell arrays. The smallest function can now be defined like this

function val = smallest (varargin)
  val = min ([varargin{:}]);
endfunction

This implementation handles any number of input arguments, but it's also a very simple solution to the problem.

A slightly more complex example of varargin is a function print_arguments that prints all input arguments. Such a function can be defined like this

function print_arguments (varargin)
  for i = 1:length (varargin)
    printf ("Input argument %d: ", i);
    disp (varargin{i});
  endfor
endfunction

This function produces output like this

print_arguments (1, "two", 3);
     -| Input argument 1:  1
     -| Input argument 2: two
     -| Input argument 3:  3

Function File: [reg, prop] = parseparams (params)
Return in reg the cell elements of param up to the first string element and in prop all remaining elements beginning with the first string element. For example

[reg, prop] = parseparams ({1, 2, "linewidth", 10})
reg =
{
  [1,1] = 1
  [1,2] = 2
}
prop =
{
  [1,1] = linewidth
  [1,2] = 10
}

The parseparams function may be used to separate 'regular' arguments and additional arguments given as property/value pairs of the varargin cell array.

See also varargin

ISBN 095461206XGNU Octave Manual Version 3See the print edition