Octave Wiki | RecentChanges

VariableLengthReturnLists

A function can be set up to return any number of values by using the special return value varargout.

Inside the function, varargout is a one-rowed cell array and should be referred to as such. This holds even if the function is called for zero or one return values.

The number of return values requested is stored in the variable nargout inside the function.

For example, the function

    function varargout = divide (dividend, divisor)
      
      quotient = dividend / divisor;
 
      switch (nargout)
        case {0,1}
          varargout = {quotient};
        case 2
          quotient = fix (quotient);
          varargout = {quotient, dividend - quotient*divisor};
        otherwise
          usage ("quotient = divide (dividend, divisor), or");
          usage ("[quotient, remainder] = divide (dividend, divisor)");
      endswitch
    endfunction

returns either the simple quotient or the integer quotient and (possibly floating point) remainder if called for one or two return values.

Thus:

    octave> divide (5, 3), q = divide (5, 3), [q, r] = divide (5, 3); [q,r]
    ans = 1.6667
    q = 1.6667
    ans =
      1  2

This example didn't really require varargout, and could instead have been defined as function [q, r] = divide (dd, dr) as described in the Manual under "Multiple Return Values".

Note that when a command consists simply of a function call, nargout is zero, but if the function is on the right-hand side of an assigment or is passed as a argument to another function, nargout is one. Hence with

    function varargout = nargout_test ()
      varargout = cell (1, nargout);
    endfunction

we have

    octave> nargout_test ()
    octave> disp (nargout_test ())
    [](0x0)
    octave> a = nargout_test ()
    a = [](0x0)
    octave> [a, b] = nargout_test ()
    a = [](0x0)
    b = [](0x0)
    octave> 

As an example of a function that does require varargout, consider:

    function varargout = multiassign (data)
      for k=1:nargout
        varargout{k} = data(:,k);
      endfor
    endfunction

which assigns the columns of a matrix (or elements of a row vector) to the return values (thus slightly generalizing the standard Octave function deal):

    octave> A = (1:2)'*(1:3)
    A =
    
      1  2  3
      2  4  6
    
    octave> [a, b, c] = multiassign (A)
    a =
    
      1
      2
    b =
    
      2
      4
    
    c =
    
      3
      6
    
    octave> [a, b, c] = multiassign (A(1,:))
    a = 1
    b = 2
    c = 3
    octave>