Matlab中动态结构生成 [英] dynamic structure generation in Matlab
问题描述
我有一个字段名列表,想要生成一个嵌套结构.我试过了:
I have a list of field names and want to generate a nested struct. I tried this:
fn1 = {'a', 'b', 'c'};
fn2 = {'d', 'e', 'f'};
s = struct();
for n1=fn1
for n2=fn2
s.(n1).(n2) = 0 ;
end
end
但是Matlab抱怨符号.{fieldname)"仅用于动态结构引用(动态结构引用的参数必须计算为有效的字段名称.").
but Matlab complaint that the notation ".{fieldname)" is for dynamic structure reference only ("Argument to dynamic structure reference must evaluate to a valid field name.").
我知道一个有效的解决方案是使用isfield()和struct()遍历字段名称. 所以我如何在不使用isfield()和struct()的情况下实现此目标,例如通过一些匿名函数和向量化?谢谢
I know a solution that works is to loop over the field names, using isfield() and struct(). So how can I achieve this goal without using isfield() and struct(), e.g. by mean of some anonymous function and vectorization? Thanks
推荐答案
您的主要问题是n1
和n2
是单元格数组,它们不是有效的结构名.因此,写作
Your main problem is that n1
and n2
are cell arrays, which are not valid struct names. Thus, writing
s.(n1{1}).(n2{1}) = 0;
修复错误.
但是,更好的方法可能是使用 CELL2STRUCT 创建s
:
However, a better method might be to use CELL2STRUCT to create s
:
s2 = cell2struct(cell(size(fn2(:))),fn2(:));
s = cell2struct(repmat({s2},size(fn1(:))),fn1(:))
这篇关于Matlab中动态结构生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!