1
我想用结构向量化操作,并花了几个小时搜索,但找不到解决方案。 我有一个结构如下:向量化和分配结构和字段
clear all
n= 10;
for i=1:n
mystruct(i).x = i;
mystruct(i).y = i;
mystruct(i).z = 0;
end
我想所有的x添加到所有y值,并将它们分配到z。
这工作:
test1 = [mystruct.x] + [mystruct.y];
test2 = arrayfun(@(a)mystruct(a).x+mystruct(a).y,1:n);
然而,分配数组不:
mystruct.z = [mystruct.x] + [mystruct.y];
mystruct.z = mystruct.x + mystruct.y;
我可以生成一个新的结构:
mystruct2 = struct('z',num2cell ([mystruct.x]+[mystruct.y]));
但接下来的操作再次没有按't work:
mystruct.z = mystruct2.z;
我当然可以用一个for循环:
for i=1:n
mystruct(i).z = mystruct(i).x + mystruct(i).y;
end
但是,这不是我想要的,因为这会让我的代码很讨厌,不会使用“PARFOR”平行作业工作。 如何执行此操作?
如果n是mystruct的长度,那么mystruct(1:n).x和mystruct.x是相同的。 – SCFrench