MATLAB Answers

0

Why do I have to create empty object array before calling constructor in constructor?

Asked by Mark Mikofski on 3 Aug 2011
Latest activity Commented on by Mark Mikofski on 14 May 2015
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

  0 Comments

Sign in to comment.

1 Answer

Answer by Mark Mikofski on 3 Aug 2011
 Accepted 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

  1 Comment

here's another example of this behavior with doubles:
>> clear
>> x= 1.23 # <1x1 double>
x =
1.23
>> x(10) = 5 # grow x to <1x10 double>
x =
1.23 0 0 0 0 0 0 0 0 5.00
>> y(10) = 5 # create <1x10 double>
y =
0 0 0 0 0 0 0 0 0 5

Sign in to comment.