Programming Functions with Multiple Outputs

Programming Functions with Multiple Outputs


I came across this problem when trying to test behavior between two functions (basically an ad hoc test suite).

If you have a function which returns a number of outputs, depending on how it’s called, you might be interested in collecting all the outputs. Something like this:

[a, b, c, d] = fun(args{:});


Except that we will sometimes only want a:c and other times a:f depending on what args looks like etc.

This may be in a test suite, where the number of input arguments determines the number of outputs. You obviously want to capture them all.

This may seem trivial to some of you, but here’s a possible solution, assuming the number of outputs matches the number of inputs (which may be arbitrarily long):


numOutputs = length(args);

out = cell(numOutputs,1);

[out{:}] = fun(args{:});


This will work as long as you know how many outputs are expected ahead of time (or can calculate it).

I hope someone finds this useful.


What Can I Do Next?

Follow us