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

조회 수: 5 (최근 30일)
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

채택된 답변

Mark Mikofski
Mark Mikofski 2011년 8월 3일
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
Mark Mikofski
Mark Mikofski 2015년 5월 14일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by