我有一个嵌套结构数组t,格式为t.a.b = value,其中a和b只是随机字符串. t可以具有任意数量的a作为字段名称,并且每个a可以具有任意数量的b作为字段名称.我需要制作一个名为x的副本,但是设置所有x.a.b = 0.另外,我需要以y.a = 0的形式为t中的所有a创建另一个结构数组.现在我正在使用嵌套的for循环解决方案,但如果有太多的a和b,它太慢了.有人能告诉我是否有任何方法可以对此嵌套循环或此代码中的任何其他操作进行矢量化,以使此代码运行得更快?谢谢.
names1 = fieldnames(t);
x = t;
y = {};
for i=1:length(names1)
y.(names1{i}) = 0;
names2 = fieldnames(x.(names1{i}));
for j=1:length(names2)
x.(names1{i}).(names2{j}) = 0;
end
end
样品:
if t is such that
t.hello.world = 0.5
t.hello.mom = 0.2
t.hello.dad = 0.8
t.foo.bar = 0.7
t.foo.moo = 0.23
t.random.word = 0.38
then x should be:
x.hello.world = 0
x.hello.mom = 0
x.hello.dad = 0
x.foo.bar = 0
x.foo.moo = 0
x.random.word = 0
and y should be:
y.hello = 0
y.foo = 0
y.random = 0