Convenient nargout Behavior
Here's a question that was recently posed at MathWorks.
I'm trying to invoke a function handle. It either returns 0 or 1 output arguments. If it returns an output argument, I want to get it; if not I would like to just invoke the function and be on my way. I have no way of knowing ahead of time whether the function returns something or not.
This situation can arise when you are building an application in which you expect to work with user-supplied functions. You can solve this using try construct, but this situation arises frequently enough that we decided to introduce the nargout bump. So what happens?
Contents
nargout Bump from 0 to 1
Many MATLAB functions return 1 result even when called with an nargout is 0. For these, here's a technique that may be of interest. It allows for a bump in nargout on the left-hand side.
Let's assume the variable c is unitialized and then call a function f.
[c{1:0}] = f(...);
f is called with nargout of 0, because 1:0 is an empty vector. If f returns no arguments, c is an empty cell. However, if f returns a result, c is a 1x1 cell containing that result.
Why does nargout Behave this Way?
Since this is not a widely known technique, I'll explain one more use of it. Suppose you are writing a function foo, and after some preparation you want foo to return all of the results, if any, of a call on bar, passing along to bar the number of arguments given to foo. The template looks like this.
function varargout = foo(...) ... whatever ... [varargout{1:nargout}] = bar(...);
Anonymous functions use exactly this technique to pass along nargout to their body and to return that body's results as the result of the anonymous function. This requirement on anonymous functions, and the observation that a significant number of other functions work in the same way, is why we introduced the bump.
Will this Simplify Some Code?
I wonder if this information allows you to simplify some of your code. Please share your results here.
- Category:
- Best Practice,
- Less Used Functionality,
- Robustness