MATLAB: Handling different numbers of arguments with builtin(‘subsref’ …)

builtinMATLABsubsref

I want to be able to overload the . operator using subsref in order to access named data streams in an object as if they were just fields – so do something like:
class DataContainer
properties
xdata
ydata
zdata
end
methods
%... constructor ...
%... other methods
function result = subsref(this, S)
if(strcmp(S.type, '.'))
switch 'X'
result = this.xdata;
switch 'Y'
result = this.ydata;
switch 'Z'
result = this.zdata;
otherwise
result = builtin('subsref', this, S);
end
end
The otherwise clause covers the case where I wish to call a normal object function using the . syntax.
However, the problem is that there is no way I can see to anticipate the number of output arguments that would be returned from the object function. If there were no arguments returned, then the above code would return an error as there would be too many output arguments.
The only possible workrounds I can see are:
(1) To always call the normal member functions without the . syntax: memFunc(this, args) (2) The following horrible hack which only works for zero or 1 argument
otherwise
bulitin('subsref', this, S);
if(exist('ans', 'var'))
result = ans;
else
result = [];
end
Both of these are unsatisfactory as I normally use the . syntax for object functions, and don't want to impose the requirement that the alternative syntax be used, and the second one is unsatisfactory as it won't work if there are more than one output arguments because 'ans' is only set to the first output.
Are there any other workrounds that I might have missed?
PS it might be asked why on earth I'd want to do this – and not just make the properties X,Y,Z. The reason is it is a generic data container importing data from a binary file, and I do not know in advance what the names of the different streams are going to be.

Best Answer

If you were looking to have comma-separated-list expansion overloaded, then you're out of luck, I think. It's an age old and unfortunate limitation of builtin('subsref',...) and given that it's been out there for 10+ years, I don't foresee any solutions soon :(
Other than that scenario, however, you should use nargout to predict the number of outputs,
[result{1:nargout}] = builtin('subsref', this, S);