Hi, have a class like this
classdef someClass
properties
name
value
end
methods
function obj = someClass(name)
obj.name(name)
end
end
I would like to create an array of objects of that class. So if I have the names= ('a','b','c') I would like to have an array a of 3 objects with a(1).name='a' a(2).name='b' a(3).name='c'
how do I have to structure my constructor to achieve this by calling
a(1:numel(names))=someClass(names)
or how can I do this in another halfway smart way. Thanks, C

 채택된 답변

Titus Edelhofer
Titus Edelhofer 2012년 6월 19일

3 개 추천

Hi,
something like this?
classdef someClass
properties
name
value
end
methods
function obj = someClass(name)
if ~nargin
% the default constructor. Needed for array creation
obj.name = '';
else
% only take care of the array part for simplicity:
if iscell(name)
[obj(1:length(name)).name] = deal(name{:});
end
end
end
end
end
You can call then as
a = someClass({'a' 'b' 'c'});
Titus

댓글 수: 4

Christof
Christof 2012년 6월 19일
Thanks a lot Titus, this works great. However, i run into troubles when I want to do more than assign just the names in the constructor, as the constructor now seems to be called twice (independent of the number of elements in the name cell). Does anyone have an idea why that is?
So, if I add the line
display('object created')
I get the following output
>> a = someClass({'a' 'b' 'c' 'd' 'e'});
object created
object created
Titus Edelhofer
Titus Edelhofer 2012년 6월 21일
Yes, that's right: if you use the debugger, you see, that in the first call the constructor is called without input argument (the default constructor). This is needed to construct the object itself (without parameters). The second call constructs the individual objects using the parameter "name". So: put into the if ~nargin the default values, whereas the "real" construction is in the else-part. If that answers the question, you might mark the question as answered ;-).
Sean de Wolski
Sean de Wolski 2012년 6월 21일
Nice Titus, learn something every day!
Kye Taylor
Kye Taylor 2012년 6월 21일
When I debug, I see that the first call is with input, and the second call is without. Is my debugger being fishy, or is something nonconstant across machines?

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data Type Identification에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by