Using subsref on a class with a robust . operator?

3 ビュー (過去 30 日間)
Ian
Ian 2012 年 8 月 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.

採用された回答

Steve Edwards
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 件)

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by