MATLAB: Do I have to create empty object array before calling constructor in constructor

arrayclassclassdefconstructoremptyhandleMATLABobjectoop

If I call constructor in the workspace using MATLAB's cheap copies, I get an object array that is exactly what MATLAB's help documentation says. Ex. #1
>> obj(3) = myClass(1,2);a = [obj.a],b = [obj.b]
a =
2 2 1
b =
4 4 2
But if I put the same commands in the constructor, I get an object array that is nearly the same, except that the first element now only has the defaults from my properties block. Ex. #2
>> obj = myClass(1,2,3);a = [obj.a],b = [obj.b]
a =
999 2 1
b =
999 4 2
Unless I create an empty object array first. Ex. #3
>> obj = myClass(1,2,3);a = [obj.a],b = [obj.b]
a =
2 2 1
b =
4 4 2
The examples above use the following m-file:
classdef myClass < handle
properties
a = 999
b = 999
end
methods
function obj = myClass(a,b,c)
if nargin<3
c = 1;
end
if c>1
% uncomment for Ex. #3
% obj = myClass.empty(0, c);
obj(c) = myClass(a,b);
else
if nargin<1
a = 2;
end
obj.a = a;
if nargin<2
b = 4;
end
obj.b = b;
end
end
end
end

Best Answer

When the constructor is called, it instantiates the object with any defaults given in the properties block ([] for any properties without defaults), so in my example above, a scalar object was already instantiated.
If c>2 the call
obj(c) = myClass(a,b);
requires MATLAB to fill in
obj(2:c-1)
with cheap copies (created by calling the constructor without arguments). Calling the empty method replaces the object with an empty array, so the call
obj(c) = myClass(a,b);
now acts as expected.
Another option would be to delete the default object before expanding it.
obj.delete
BTW: MATLAB states that an object is destroyed if its variable is assigned to a new value or when the function ends, so you do not need to free memory. http://www.mathworks.com/help/techdoc/matlab_oop/brfylzt-1.html#bsxw4_c