MATLAB: How can an object array be extented by itself

MATLABoopoop objectarray

I would like an object array to be able to extend itself. I tried the example below but the size of the object array (5×1) does not change to (6×1). 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

Best Answer

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