Using subsref on a class with a robust . operator?
显示 更早的评论
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 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Data Import from MATLAB 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!