MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   Matlab中动态结构生成 (https://www.labfans.com/bbs/showthread.php?t=26587)

poster 2019-12-14 20:13

Matlab中动态结构生成
 
我有一个字段名列表,想要生成一个嵌套结构。我尝试了这个:

fn1 = {'a', 'b', 'c'}; fn2 = {'d', 'e', 'f'}; s = struct(); for n1=fn1 for n2=fn2 s.(n1).(n2) = 0 ; end end 但是Matlab抱怨符号“。{fieldname)”仅用于动态结构引用(“动态结构引用的参数必须计算为有效的字段名称。”)。

我知道一个有效的解决方案是使用isfield()和struct()遍历字段名称。那么,如何在不使用isfield()和struct()的情况下(例如通过一些匿名函数和向量化)实现这一目标?谢谢



[B]回答:[/B]

您的主要问题是n1和n2是单元格数组,它们不是有效的结构名。因此,写作

s.(n1{1}).(n2{1}) = 0; 解决错误。

但是,更好的方法可能是使用[URL="http://www.mathworks.com/help/techdoc/ref/cell2struct.html"]CELL2STRUCT[/URL]创建s :

s2 = cell2struct(cell(size(fn2(:))),fn2(:)); s = cell2struct(repmat({s2},size(fn1(:))),fn1(:))

[url=https://stackoverflow.com/questions/5291331]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 09:05

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.