how to use indexing in array of objects?
5 views (last 30 days)
Show older comments
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!
0 Comments
Answers (2)
David Young
on 17 Mar 2012
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 Comment
Daniel Shub
on 17 Mar 2012
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.
0 Comments
See Also
Categories
Find more on Customize Object Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!