フィルターのクリア

array of objects

4 ビュー (過去 30 日間)
Christof
Christof 2012 年 6 月 19 日
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 日
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 件のコメント
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 件)

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by