how to use indexing in array of objects?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
David Young
el 17 de Mzo. de 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 comentario
Daniel Shub
el 17 de Mzo. de 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 comentarios
Ver también
Categorías
Más información sobre Customize Object Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!