使用相互依赖的迭代向量化循环

时间:2015-12-19 15:34:44

标签: performance matlab vectorization

r是一个向量:

23 1 24 5 4 3 7 8

L是矢量。

L=
 2, 4, 6, 5, 3

我正在尝试对这段代码进行矢量化。由于迭代是相互依赖的(即prev_weight = prev_weight - weight_from),我无法找到一种好的矢量化方法。目标显然是最小化执行时间。

    total_weight = sum(r(L));
    prev_weight = total_weight;

    len=length(L);

    dist = 0.0;
    for i=2:len-1
        from=L(i);
        to=L(i+1);
        dist = dist + d(from,to) * prev_weight;
        weight_from = r(from);
        prev_weight = prev_weight - weight_from;
    end

1 个答案:

答案 0 :(得分:3)

该依赖关系可以追溯cummulative sum操作,这构成了下面列出的矢量化解决方案的基础 -

%// Vectorized way to get "d(from,to)" across all iterations with SUB2IND
vals = d(sub2ind(size(d),L(2:end-1),L(3:end)))

%// Vectorized way to get "r(from)" as we already have all "from" indices
weight_from1 = r(L(2:end-1))

%// Magic happens here as we trace the dependency with cumsum and thus
%// get all previous weights in one go
prev_weight1 = total_weight - [0 cumsum(weight_from1(1:end-1))]

%// Finally get the distance with elementwise multiplication and summing
%// being simulated with dot product
dist_out = vals*prev_weight1.'