Next: , Previous: , Up: Functions and Scripts   [Contents][Index]


11.5 Variable-length Return Lists

It is possible to return a variable number of output arguments from a function using a syntax that’s similar to the one used with the special varargin parameter name. To let a function return a variable number of output arguments the special output parameter name varargout is used. As with varargin, varargout is a cell array that will contain the requested output arguments.

As an example the following function sets the first output argument to 1, the second to 2, and so on.

function varargout = one_to_n ()
  for i = 1:nargout
    varargout{i} = i;
  endfor
endfunction

When called this function returns values like this

[a, b, c] = one_to_n ()
     ⇒ a =  1
     ⇒ b =  2
     ⇒ c =  3

If varargin (varargout) does not appear as the last element of the input (output) parameter list, then it is not special, and is handled the same as any other parameter name.

: [r1, r2, …, rn] = deal (a)
: [r1, r2, …, rn] = deal (a1, a2, …, an)

Copy the input parameters into the corresponding output parameters.

If only a single input parameter is supplied, its value is copied to each of the outputs.

For example,

[a, b, c] = deal (x, y, z);

is equivalent to

a = x;
b = y;
c = z;

and

[a, b, c] = deal (x);

is equivalent to

a = b = c = x;

Programming Note: deal is often used with comma separated lists derived from cell arrays or structures. This is unnecessary as the interpreter can perform the same action without the overhead of a function call. For example:

c = {[1 2], "Three", 4};
[x, y, z] = c{:}
⇒
   x =

      1   2

   y = Three
   z =  4

See also: cell2struct, struct2cell, repmat.


Next: Variable-length Argument Lists, Previous: Multiple Return Values, Up: Functions and Scripts   [Contents][Index]