Hi, I wanted to overload subsref in a class to use the {} notation to index a class property (obj.stimuli below):
classdef MyDataClass properties stimuli = [] info = '' end properties (SetAccess = private) Date end methods function obj = MyDataClass() obj.stimuli = {'hickory';'dickory';'dock'}; obj.info = 'example class'; obj.Date = clock; end function sref = subsref(obj,s) switch s(1).type case '.' sref = builtin('subsref',obj,s); case '()' sref = builtin('subsref',obj,s); case '{}' sref = builtin('subsref',obj.stimuli,s); end end function testMe(obj) for i = 1:size(obj.stimuli,1) fprint('%s ',obj.stimuli{i}); end printf('\n') end function out = mySize(obj) out = size(obj.stimuli,1); end endend
However, the problem is that overloading the . operator causes problems because now unless every method returns a value (testMe doesn't, mySize does in the example), then subsref will fail:
>> m=MyDataClass
m =
MyDataClassProperties: stimuli: {3x1 cell} info: 'example class' Date: [2012 8 30 18 3 40.5521]Methods
>> m{1}
ans = hickory
>> m.info
ans = example class
>> m.mySize
ans = 3
>> m.testMe
Error using MyDataClass/testMeToo many output arguments.Error in MyDataClass/subsref (line 18) sref = builtin('subsref',obj,s);
What is the best way to handle this robustly? Having to parse each s.subs name to call builtin will fix this but is not very elegant and liable to break as the class grows. I basically need something like a varargout.
Best Answer