How can an object array be extented by itself?

5 visualizaciones (últimos 30 días)
Martin Schmidt
Martin Schmidt el 26 de Oct. de 2015
Comentada: Martin Schmidt el 27 de Oct. de 2015
I would like an object array to be able to extend itself. I tried the example below but the size of the object array (5x1) does not change to (6x1). Of couse I can append an object to the object array outside, but what about inside the object array?
classdef TestAdd < handle
properties
val=1;
end
methods
function obj=TestAdd(n)
if nargin>0
obj(n,1)=TestAdd;
for ii=1:n
obj(ii,1).val=ii;
end
end
end
function add(obj)
N=length(obj)+1;
obj(end+1,1)=TestAdd;
obj(N,1).val=N;
end
end
end
Command line in/output
>> a=TestAdd(5)
a =
5x1 TestAdd array with properties:
val
>> a.add()
>> a
a =
5x1 TestAdd array with properties:
val

Respuesta aceptada

Titus Edelhofer
Titus Edelhofer el 26 de Oct. de 2015
Hi,
interesting observation. I would explain as follows: the handle property means, that we use references to objects instead of the objects themselves. This means, that you can manipulate object properties without the need to return the changed object.
The structure of the object itself is not falling into this handle behavior. So you need to return the (new) object.
function obj = add(obj)
N=length(obj)+1;
obj(end+1,1)=TestAdd;
obj(N,1).val=N;
end
Now you call as follows:
>> o = TestAdd(5)
o =
5x1 TestAdd array with properties:
val
>> o = o.add
o =
6x1 TestAdd array with properties:
val
Of course you can encapsulate this into a new class if you like :).
Hope this helps,
Titus
  1 comentario
Martin Schmidt
Martin Schmidt el 27 de Oct. de 2015
That works. Thanks! I'm afraid that this seems to be the only way. As the use of the add function is not intuitiv I will add a nargout check because without output argument the add function is useless.

Iniciar sesión para comentar.

Más respuestas (1)

Guillaume
Guillaume el 26 de Oct. de 2015
I find matlab's concept that an array of objects is the same type as the objects themselves very very wrong and I would avoid relying on this.
If I were you I would have a second class that is dedicated to handling the array.
I'm not sure why your example fails. My guess would be the array of object isa object concept breaks down when you try to modify the array size outside of the constructor. The doc on array of objects is so sparse that it's difficult to know what is or isn't supposed to work.
  1 comentario
Martin Schmidt
Martin Schmidt el 27 de Oct. de 2015
I actually think you are right and started with an object holding a list the objects, but the handling of object arrays was a bit easier in the end.

Iniciar sesión para comentar.

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by