Is it possible to create a structure with fields but without defined values?

58 ビュー (過去 30 日間)
Mr M.
Mr M. 2015 年 7 月 1 日
回答済み: Walter Roberson 2015 年 7 月 2 日
Is it possible to create a structure with fields but without defined values? and add values to the structure later?

回答 (2 件)

Walter Roberson
Walter Roberson 2015 年 7 月 2 日
Muthu's answer is completely correct for producing a structure array with one member with defined fields which have been initialized to [] .
Sometimes, though, what you want is to create a structure with no members but which has defined fields. The method for doing that is not obvious but is
z = struct('fieldname1',{},'fieldname2',{})
the output of that would be a 0 x 0 structure which has the given fields.
Pre-defining an empty structure can be important in some cases involving copying members between structures, or appending structure members. For example, using the z I defined here:
>> cell2mat({[], struct('fieldname1', 3, 'fieldname2', 'hello')})
Error using cell2mat (line 45)
All contents of the input cell array must be of the same data type.
>> cell2mat({z, struct('fieldname1', 3, 'fieldname2', 'hello')})
ans =
fieldname1: 3
fieldname2: 'hello'

Muthu Annamalai
Muthu Annamalai 2015 年 7 月 1 日
Yes.
z = struct('fieldname1',[],'fieldname2',[])
z.fieldname1
z.fieldname2

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by