Matlab : Object array indexing by property -
in matlab, create array of objects can pick element 1 of unique property while keeping same behavior normal indexing.
here class:
classdef myclass < dynamicprops properties name = ''; values end methods function obj = myclass(name,values) if nargin > 0 obj.name = name; obj.values = values; end end end end
lets consider following array :
>> a(1) = myclass('one' ,[1:10]); >> a(2) = myclass('two' ,[2:20]); >> a(3) = myclass('three',[3:30]);
the easiest way directly acess values of element :
>> a(1).values ans = 1 2 3 4 5 6 7 8 9 10
but call elements of array name not index, while keeping ability have direct access values :
>> % /!\ intended behavior, not real result >> a('two').values(end-2:end) * 3 ans = 54 57 60
i une two = findobj(a,'name','two'); two.values(end-2:end) * 3
it's not convinient.
i've tried setting custom subsref
method object , works quite lose indexing features.
i got intended behavior following method :
function out = subsref(obj,s) if strcmpi(s(1).type,'()') && ischar(s(1).subs{1}) found = findobj(obj,'name',s(1).subs{1}); if ~numel(found) error(['object name ''' s(1).subs{1} ''' not found.']) end if numel(s) == 1 out = found(1); else out = builtin('subsref',found(1),s(2:end)); end else out = builtin('subsref',obj,s); end end
but can't names/values [a.values]
or {a.name}
. matlab returns :
error using myclass/subsref many output arguments.
and might lose other indexing features well.
is there better solution problem ? appreciated.
you can use varargout
in subsref
support getting list of values of property values
:
function varargout = subsref(obj,s) if strcmpi(s(1).type,'()') && ischar(s(1).subs{1}) && ... ~strcmp(s(1).subs{1},':') found = findobj(obj,'name',s(1).subs{1}); if ~numel(found) error(['object name ''' s(1).subs{1} ''' not found.']) end if numel(s) == 1 varargout{1} = found(1); else varargout{1} = builtin('subsref',found(1),s(2:end)); end else [varargout{1:nargout}] = builtin('subsref',obj,s); end end
note added ~strcmp(s(1).subs{1},':')
condition in first if
support a(:)
indexing.
one other consideration see how handle multiple strings:
a('one','two');
or mixed types:
a('one',3:end);
these more corner cases, consider.
Comments
Post a Comment