Reputation: 3397
Why does my Instantiate function not create a 'Blank' instance of That?
I have the following minimal class :
classdef That < handle
properties
This = ''
end
methods
function Self = That(String)
if exist('String','var') == 1
Self.This = String;
end
end
function Self = Instantiate(Self)
if isempty(Self)
Self(1,1) = That;
end
end
end
end
If I run
This = That;
disp(size(This)) % 1x1
disp(isempty(This)) % False
and it's all good, I have a 'Blank' instance of the class
If I run
TheOther = That.empty;
disp(size(TheOther)) % 0x0
disp(isempty(TheOther)) % True
TheOther.Instantiate;
disp(size(TheOther)) % 0x0 - Expecting 1x1
disp(isempty(TheOther)) % True - Expecting False
As you can see running my Instantiate doesn't work and I can't see why ? Surely it should replace the empty instance with a non empty, yet blank, one ?
UPDATE :
The Link from SCFrench lead to this http://www.mathworks.com/help/techdoc/matlab_oop/brd4btr.html under the heading Creating Empty Arrays, though this didn't work either :
function Self = Instantiate(Self)
if isempty(Self)
Blank = That;
Props = properties(Blank)
for idp = 1:length(Props)
Self(1,1).(Props{idp}) = Blank.(Props{idp});
end
end
end
Upvotes: 3
Views: 857
Reputation: 8374
MATLAB passes arrays of handle objects (including 1-by-1 "scalar" arrays) by value. A handle value is a reference to an object, which can be used to change the state of the object (i.e. its properties), but importantly, it is not the object itself. If you pass an array of handle values to a function or method, a copy of the array is actually passed to the function, and modifying the dimensions of the copy has no effect on the original. In fact, when you call
TheOther.Instantiate;
The instance of That
that you assigned to Self(1,1)
gets returned as the output of Instantiate
and assigned to ans
.
This link to a section of MATLAB Object-Oriented Design documentation might also help.
Upvotes: 2
Reputation: 124563
Maybe you should make it a static function:
methods (Static)
function Self = Instantiate(Self)
if isempty(Self)
Self(1,1) = That;
end
end
end
Then:
>> TheOther = That.empty;
>> size(TheOther)
ans =
0 0
>> isempty(TheOther)
ans =
1
>> TheOther = That.Instantiate(TheOther);
>> size(TheOther)
ans =
1 1
>> isempty(TheOther)
ans =
0
Upvotes: 0