Using subsref on a class with a robust . operator?
3 次查看(过去 30 天)
显示 更早的评论
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
end
end
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 =
MyDataClass
Properties:
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/testMe
Too 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.
0 个评论
采纳的回答
Steve Edwards
2012-8-30
Hi Ian, It turns out that subsref does have a varargout signature (it's just not documented). Here's the function signature you want:
function varargout = subsref(obj,s)
varargout{1:nargout} = builtin('subsref',obj,s);
end
You would probably want to make sure that '.' and '{}' use the varargout functionality, as they can both return comma separated lists. I'm also guess that you'll want to overload numel for your brace indexing.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!