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

If you wish to use a style where a variable will be left to fall into the bit bucket, then a reasonable alternative is

[ans, ans, variableThatIWillUse] = myfun(inputs);

ans is of course the default junk variable for MATLAB, getting overwritten often in the course of a session.

While I do like the new trick that MATLAB now allows, using a ~ to designate an ignored return variable, this is a problem for backwards compatibility, in that users of older releases will be unable to use your code.

I generally avoid using new things like that until at least a few MATLAB releases have been issued to ensure there will be very few users left in the lurch. For example, even now I find people are still using an old enough MATLAB release that they cannot use anonymous functions.


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.


This is somewhat of a hack, but it works:

First a quick example function:

Func3 = @() deal(1,2,3);
[a,b,c]=Func3();
% yields a=1, b=2, c=3

Now the key here is that if you use a variable twice on the left-hand side of a multiple-expression assignment, an earlier assignment is clobbered by the later assignment:

[b,b,c]=Func3();
% yields b=2, c=3

[c,c,c]=Func3();
% yields c=3

(Just to check, I also verified that this technique works with [mu,mu,mu]=polyfit(x,y,n) if all you care about from polyfit is the third argument.)


There's a better approach; see ManWithSleeve's answer instead.