This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Support Variable Number of Outputs

This example shows how to define a function that returns a variable number of output arguments using varargout. Output varargout is a cell array that contains the function outputs, where each output is in its own cell.

Create a function in a file named magicfill.m that assigns a magic square to each requested output.

function varargout = magicfill
   nOutputs = nargout;
   varargout = cell(1,nOutputs);

   for k = 1:nOutputs
      varargout{k} = magic(k);

Indexing with curly braces {} updates the contents of a cell.

Call magicfill and request three outputs.

[first,second,third] = magicfill
first =

second =
     1     3
     4     2

third =
     8     1     6
     3     5     7
     4     9     2

MATLAB® assigns values to the outputs according to their order in the varargout array. For example, first == varargout{1}.

You can use varargout alone in an output argument list, or at the end of the list of outputs, such as

function [x,y,varargout] = myfunction(a,b)

In this case, varargout{1} corresponds to the third output that the function returns, and nargout returns length(varargout) + 2.

See Also


Related Examples

More About