Why the second one gives rise to empty struct?
s.a=1; s.b=2; s.c={}
s =
a: 1
b: 2
c: {}
s = struct('a',1,'b',2,'c',{})
s =
0x0 struct array with fields:
a
b
c

 採用された回答

per isakson
per isakson 2014 年 11 月 24 日
編集済み: per isakson 2014 年 11 月 24 日

1 投票

That's the way the function struct is designed to work. See struct, Create structure array "[...]If value is an empty cell array {}, then s is an empty (0-by-0) structure."

4 件のコメント

Ray Lee
Ray Lee 2014 年 11 月 24 日
OK.
So I should use s = struct('a',1,'b',2,'c',struct([]))
per isakson
per isakson 2014 年 11 月 24 日
編集済み: per isakson 2014 年 11 月 24 日
Or why not
s = struct('a',1,'b',2,'c',[]);
I guess it depends on the context. I don't really see the need. Do you intend to assign struct-values to s.c ?
Guillaume
Guillaume 2014 年 11 月 24 日
編集済み: Guillaume 2014 年 11 月 24 日
If you do want to assign an empty cell array to a field of a structure using the struct function, you need to wrap that empty cell array into a cell array:
s = struct('a', 1, 'b', 2, 'c', {{}})
s =
a: 1
b: 2
c: {}
For that matter, even if the cell array is not empty you still need to wrap it to assign it to a scalar structure, otherwise the elements of the cell arrays are just distributed over an array of structs.
Ray Lee
Ray Lee 2014 年 11 月 26 日
good solution.
in my code, I checked if s.c is empty. if not, the code makes some processing using the parameters in s.c

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Structures についてさらに検索

質問済み:

2014 年 11 月 24 日

コメント済み:

2014 年 11 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by