use*_*502 6 matlab for-loop nested structure vectorization
我有一个嵌套结构数组t,格式为tab = value,其中a和b只是随机字符串.t可以具有任意数量的a作为字段名称,并且每个a可以具有任意数量的b作为字段名称.我需要制作一个名为x的副本,但是设置所有xab = 0.另外,我需要以ya = 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
Run Code Online (Sandbox Code Playgroud)
样品:
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
Run Code Online (Sandbox Code Playgroud)
要构造y,您可以执行以下操作:
>> 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;
>> f = fieldnames(t);
>> n = numel(f);
>> fi = cell(1,n*2);
>> fi(1:2:(n*2-1)) = f;
>> fi(2:2:(n*2)) = num2cell(zeros(n,1))
fi =
'hello' [0] 'foo' [0] 'random' [0]
>> y = struct(fi{:})
y =
hello: 0
foo: 0
random: 0
Run Code Online (Sandbox Code Playgroud)
基本上,您只是获取字段名称,将它们与元胞数组中的零交错,然后从该元胞数组直接使用逗号分隔的字段名称和值列表构造结构。
对于x,我想您恐怕仍然需要循环第一级字段名。但是您应该能够在每次循环迭代中执行与上述类似的操作。