matlabfunctionscilabreferential-transparencymultiple-variable-return

What exactly does a multi-output function in Matlab return?


Disclaimer: I'm actually using Scilab, but it's mostly very similar to MATLAB, and based on my research it seems the same phenomenon happens with MATLAB.

In MATLAB, functions can be multi-output. Suppose we have a function function [a, b] = f(x). If I type:

c = f(x)

Then c is given the value of the first output. If I type:

[a, b] = f(x)

Then [a, b] is given the value of the pair of both outputs. This seems to imply that MATLAB doesn't have referential transparency. What is the actual value of the expression f(x)? What's going on?


Solution

  • In some cases the number of requested outputs changes the behaviour, particularly when a function is called with no output arguments.

    For example, this simply plots a histogram of the data in a with the default settings:

    hist(a);
    

    The next returns the histogram data into N. No plot is produced:

    N = hist(a);
    

    However, if we ask for two outputs (X is now the bin centres) we can plot the histogram with bar (which is what hist uses internally to plot if no output arguments are given):

    [N, X] = hist(a);
    bar(X,N);
    

    This behaviour is controlled by checking nargout, and can be incorporated into your own functions.