how to use indexing in array of objects?
이전 댓글 표시
myclass inherits handle. myclass has one property named 'value'. The property 'value' is set at object construction (its set to the input argument, if any).
I create array of objects like this:
myarray(1)=myclass(randn(1,1));
myarray(2)=myclass(randn(2,2));
myarray(3)-myclass(randn(3,3));
I would like to operate on the first and third object like this:
j=[true false true];
myarray(j).value=myarray(j).value * scalar
Anyone know how to make this work? or an alternate method without loops?
Thanks!
답변 (2개)
David Young
2012년 3월 17일
My best so far (but maybe someone has a simpler way):
c = arrayfun(@(x) x.value*k, myarray(j), 'UniformOutput', false);
[myarray(j).value] = deal(c{:});
where k is your "scalar".
댓글 수: 1
Walter Roberson
2012년 3월 17일
Minor simplification:
[myarray(j).value] = c{:};
Daniel Shub
2012년 3월 17일
I think arrayfun is essentially a loop.
I think the "MATLAB" way would be to overload subsref and subsasgn.
That said, I try and avoid having to overload subsref and subsasgn at all costs. I also try to avoid object arrays. If for some reason I must have an object array, I work on each element in isolation.
EDIT This does not work since I missed that myarray(j).value chages size for every j.
A minimal subsasgn and subsref
function varargout = subsref(obj, s)
if length(s) == 2 ...
&& strcmp(s(1).type, '()') ...
&& strcmp(s(2).type, '.') ...
&& strcmp(s(2).subs, 'value')
varargout = {[obj(s(1).subs{:}).(s(2).subs)]};
else
[varargout{1:nargout}] = builtin('subsref', obj, s);
end
end
function obj = subsasgn(obj, s, val)
if isempty(obj)
obj = myclass.empty;
end
if length(s) == 2 ...
&& strcmp(s(1).type, '()') ...
&& strcmp(s(2).type, '.') ...
&& strcmp(s(2).subs, 'value')
temp = num2cell(val);
[obj(s(1).subs{:}).(s(2).subs)] = temp{:};
else
obj = builtin('subsasgn', obj, s, val);
end
end
and then you can do
myarray(j).value=myarray(j).value * scalar
If you chose not to overload subsref, then you can do
myarray(j).value=[myarray(j).value] * scalar
note the added brackets on the RHS.
카테고리
도움말 센터 및 File Exchange에서 Customize Object Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!