矢量化一个循环变量依赖于另一个的嵌套循环 [英] vectorizing a nested loop where one loop variable depends on the other
问题描述
我最近学会了如何在以前的问题我问过了。然而,现在我也试图矢量化以下循环:
$ $ $ $ $ c $ 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 )*((K-1大于0)+1);
end
end
end
end
现在 k
取决于 j
...到目前为止我尝试了什么:
<$ c(c)> B(j)*((k-1)> 0)+(c-1) 1)给出了一个三角矩阵,我设法独立地进行向量化:
B2 = tril([ (8,1)* B']');
B2(2:end,2:end)= 2 * B2(2:end,2:end);
但是,这正确地给了我(j,k)矩阵,而不是使用它来向量化剩余循环的方法。也许我在错误的路径太...那么我怎样才能矢量化这种类型的循环?
在你的意见之一到上一个问题的接受解决方案,你提到连续 bsxfun(@times,..,permute ..)
代码更快。如果是这样的话,你也可以在这里使用类似的方法。下面是使用这样一个模式的代码: 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]));
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
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);
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?
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屋!