Constructor not working, preallocating object leaves object with no properties
4 views (last 30 days)
Show older comments
function obj = ameth(t)
if nargin > 0
obj(numel(t)) = ameth;%preallocates the obj
for i=1:numel(t)
obj(i).trk = t(i);
end
end
end
This is under methods in my class definition, and is the constructor. trk is the only protected access property. When I call this method (h = ameth), I find that it returns an answer with no properties, but I am expecting to have the property trk. Where have I gone wrong?
0 Comments
Accepted Answer
per isakson
on 25 Mar 2015
Edited: per isakson
on 25 Mar 2015
Works well here (R2013b)
>> t = ameth([1:4])
t =
1x4 ameth array with properties:
trk
>> t(1).trk
ans =
1
>> [t(:).trk]
ans =
1 2 3 4
>>
where
classdef ameth
properties
trk
end
methods
function obj = ameth(t)
if nargin > 0
obj(numel(t)) = ameth;%preallocates the obj
for ii = 1:numel(t)
obj(ii).trk = t(ii);
end
end
end
end
end
 
Addendum triggered by comment
>> h = ameth([1:4])
h =
1x4 ameth array with no properties.
>> h.trk
You cannot get the 'trk' property of ameth.
>>
where
properties
is replaced by
properties( Access = protected )
4 Comments
per isakson
on 25 Mar 2015
Edited: per isakson
on 25 Mar 2015
With protected the property is visible to methods of the class itself and sub-classes, but not to other classes and the "base workspace". ("class short for "instances of class".) There are better wordings in the documentation.
More Answers (1)
Adam
on 25 Mar 2015
Edited: Adam
on 25 Mar 2015
Are you sure it has no properties? If it is a protected property you have then you will not be able to see it when you display the object on command line, you will only see it inside the object (or inside an object of a derived class), e.g. in the breakpoint of a class function and even then it will not display in command window variables.
I often make my variables public while I am still working on developing a class just so I can see them easily, then I make them private or protected once I am satisfied things are working.
2 Comments
Adam
on 25 Mar 2015
Yes, it will exist and be accessible within the class and derived classes. If you really want you can over-ride the display functions in a class to make them show private and protected properties, but I can never be bothered.
See Also
Categories
Find more on Create System Objects in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!