Wednesday, May 1, 2013

Cell arrays for collecting a variable number of output arguments in Matlab

I learned some new tricks in Matlab today for dealing with functions that return a variable number of output arguments. I honestly think that there's something less-than-ideal about Matlab if I need to employ tricks to get my code working, but that's an entirely different topic...

If, for some reason, I have a function that returns a comma-separated list of arguments, I would normally write them explicitly like this:
[output1, output2, output3] = someFunction(input1, input2);
This means that myFunction would return three arguments and store them in output1, output2, and output3.

However, I recently wrote some code in which I could not say a priori how many output arguments I was going to have. The number of outputs depended on one of my input arguments, which happened to be a function handle.

To explain what I learned, consider a function of one input called myFunction. The input argument is a function handle @myHandle. The number of output arguments that myFunction returns is the same as the function linked to @myHandle and can change depending on my implementation of @myHandle. The following code first finds the number of outputs of @myHandle, then saves the outputs from myFunction into a cell array:

numArgsOut = nargout(@myHandle);
[myOutputs{1:numArgsOut}] = myFunction(@myHandle);
Tricky, but effective. This post on Stack Overflow helped me.

Today I also learned that I can insert a tilde into a comma-separated list of output variables if I don't want to save a particular variable. For example, if I don't care about output2 from someFunction above, but I do want to keep output1 and output3, I can type (in Matlab 2009 and later)
[output1, ~, output3] = someFunction(input1, input2);