向量化一个嵌套循环,其中一个循环变量依赖于另一个 [英] vectorizing a nested loop where one loop variable depends on the other

查看:28
本文介绍了向量化一个嵌套循环,其中一个循环变量依赖于另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近学习了如何在之前的 问题 我问过.但是,现在我还尝试对以下循环进行矢量化

I've recently learned how to vectorize a "simple" nested loop in a previous question I've asked. However, now I'm trying also to vectorize the following loop

A=rand(80,80,10,6,8,8);

I=rand(size(A1,3),1);
C=rand(size(A1,4),1);
B=rand(size(A1,5),1);

for i=1:numel(I)
    for v=1:numel(C)
        for j=1:numel(B)
            for k=1:j
                A(:,:,i,v,j,k)= A(:,:,i,v,j,k)*I(i)*C(v)*B(j)*((k-1>0)+1);               
            end
        end
    end
end

所以现在 k 依赖于 j ......到目前为止我尝试了什么:jk 项的组合(即 B(j)*((k-1>0)+1) 给出了一个三角矩阵我设法独立矢量化:

So now k depends in j... What have I tried so far: The combination of j and k terms (i.e. B(j)*((k-1>0)+1) gives a triangular matrix that I manage to vectorize independently:

  B2=tril([ones(8,1)*B']');
  B2(2:end,2:end)=2*B2(2:end,2:end);

但这给了我正确的 (j,k) 矩阵,而不是使用它来矢量化剩余循环的方法.也许我也走错了路……那么我该如何矢量化这种类型的循环呢?

But that gives me the (j,k) matrix properly and not a way to use it to vectorize the remaining loop. Maybe I'm in the wrong path too... So how can I vectorize that type of loop?

推荐答案

您对上一个问题的已接受解决方案的评论之一,您提到了基于连续 bsxfun(@times,..,permute..) 的代码更快.如果是这种情况,您也可以在这里使用类似的方法.这是使用这种模式以及 tril -

In one of your comments to the accepted solution of the previous question, you mentioned that successive bsxfun(@times,..,permute..) based codes were faster. If that's the case, you can use a similar approach here as well. Here's the code that uses such a pattern alongwith tril -

B1 = tril(bsxfun(@times,B,[1 ones(1,numel(B)-1).*2]));
v1 = bsxfun(@times,B1, permute(C,[3 2 1]));
v2 = bsxfun(@times,v1, permute(I,[4 3 2 1]));
A = bsxfun(@times,A, permute(v2,[5 6 4 3 1 2]));

这篇关于向量化一个嵌套循环,其中一个循环变量依赖于另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆