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!