结构分配的矢量化

Vectorisation of structure allocation

我正在尝试将一个非常量元胞数组值分配给整个结构中的一个字段。

我写了一个 for-loop 脚本来实现这个:

n = 5;

c = {[0,0]};
b(1:n) = struct('c',c);

for i=1:5
    b(i).c(1) = i;
    b(i).c(2) = i+1;
end

但希望能够向量化 c 的分配。

是否可以将此代码矢量化,或者我最好使用数值数组?

这是适合您提供的示例的矢量化解决方案,请注意,它是为您创建的示例,但可以使用相同的逻辑轻松推广

使用您的代码我们得到以下输出:

for i=1:5
    disp(b(i))
end

c =
   1   2
c =
   2   3
c =
   3   4
c =
   4   5
c =
   5   6

矢量化实现是:

cc = [1,2];
cc_rep = repmat(cc, n, 1);
increm = 0:1:n-1;

cc_rep_in = cc_rep + increm';
cc_rep_in_cell = num2cell(cc_rep_in, 2);

bb(1:n) = struct('c', cc_rep_in_cell);

for i=1:n
    disp(bb(i))
end

我们得到以下输出:

c =
   1   2
c =
   2   3
c =
   3   4
c =
   4   5
c =
   5   6

Notice for small n your loop is a bit faster, but as it increased the suggested method is faster (first line is your loop, while the second is the suggested code):

for n=10:

Elapsed time is 0.0005548 seconds.
Elapsed time is 0.00261188 seconds.

for n=100:

Elapsed time is 0.0033648 seconds.
Elapsed time is 0.00180006 seconds.

for n=500:

Elapsed time is 0.021843 seconds.
Elapsed time is 0.00321412 seconds.