当前位置:  开发笔记 > 编程语言 > 正文

Vectorize Triple Loop - MATLAB

如何解决《VectorizeTripleLoop-MATLAB》经验,为你挑选了1个好方法。

我有以下大而非常低效的循环.

P is a [2000 x 200 x 5] matrix
D is a [2000 x 200 x 5] matrix
S is a [200 x 1005] matrix
PS is a [2000 x 1000 x 5] matrix

我想计算以下循环:

for k=1:2000
   for n=1:200
      for t=1:5
          P(k,n,t) = sum(S(n,t+1:t+1000) .* PS(k,1:1000,t));
      end
   end
end

显然这是非常低效的.我尝试过parfor,但我宁愿使用矢量化解决方案.我尝试了几件事bsxfun,但也从未设法让它发挥作用.

谢谢.



1> Divakar..:

这几乎是(几乎因为我们仍然有一个循环,但只有5次迭代)矢量化方法使用powerful matrix-multiplication-

out = zeros(2000,200,5);
for t=1:size(P,3) %// size(P,3) = 5
    out(:,:,t) = PS(:,:,t)*S(:,t+1:t+1000).';
end

运行时测试并验证输出 -

%// Inputs
D = rand(2000,200,5);
S = rand(200,1005);
PS = rand(2000,1000,5);

disp('--------------------- No Matrix-mult-fun')
tic
P = zeros(2000,200,5);
for k=1:2000
   for n=1:200
      for t=1:5
          P(k,n,t) = sum(S(n,t+1:t+1000) .* PS(k,1:1000,t));
      end
   end
end
toc

disp('--------------------- Fun fun Matrix-mult-fun')
tic
out = zeros(2000,200,5);
for t=1:size(P,3) %// size(P,3) = 5
    out(:,:,t) = PS(:,:,t)*S(:,t+1:t+1000).';
end
toc

error_val = max(abs(P(:)-out(:)))

输出 -

--------------------- No Matrix-mult-fun
Elapsed time is 70.223008 seconds.
--------------------- Fun fun Matrix-mult-fun
Elapsed time is 0.624308 seconds.
error_val =
     1.08e-12

推荐阅读
mobiledu2402851377
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有