How to elegantly ignore some return values of a MATLAB function?

Jordi picture Jordi · Apr 14, 2009 · Viewed 54.7k times · Source

Is it possible to get the 'nth' return value from a function without having to create dummy variables for all n-1 return values before it?

Let's say, I have the following function in MATLAB:

function [a,b,c,d] = func()
a = 1;
b = 2;
c = 3;
d = 4;

Now suppose, I'm only interested in the third return value. This can be accomplished by creating one dummy variable:

[dummy, dummy, variableThatIWillUse, dummy] = func;
clear dummy;

But I think this is kind of ugly. I would think that you might be able to do something like one of the following things, but you can't:

[_, _, variableThatIWillUse, _] = func;

[, , variableThatIWillUse, ] = func;

variableThatIWillUse = func(3);

variableThatIWillUse = func()(3);

Are there any elegant ways to do this that do work?


So far, the best solution is to simply use the variableThatIWillUse as a dummy variable. This saves me from having to create a real dummy variable that pollutes the work-space (or that I would need to clear). In short: the solution is to use the variableThatIWillUse for every return value up until the interesting one. Return values after can simply be ignored:

[variableThatIWillUse, variableThatIWillUse, variableThatIWillUse] = func;

I still think this is very ugly code, but if there is no better way, then I guess I'll accept the answer.

Answer

ManWithSleeve picture ManWithSleeve · Sep 10, 2009

With MATLAB Version 7.9 (R2009b) you can use a ~, e.g.,

[~, ~, variableThatIWillUse] = myFunction();

Note that the , isn't optional. Just typing [~ ~ var] will not work, and will throw an error.

See the release notes for details.