【问题标题】:Is there a way to vectorize this for loop有没有办法向量化这个 for 循环
【发布时间】:2016-06-17 07:07:59
【问题描述】:

有没有办法将这个 for 循环向量化以加快速度?

谢谢

        for j =1 :size(Rond_Input2Cell,1)

            for k=1: size(Rond_Input2Cell,2)

                Rond_Input2Cell(j,k)=  (Pre_Rond_Input2Cell(j,k)*Y_FGate(k))+(net_Cell(k)*Y_InGate(k)*tmp_input(j)) ;

            end
        end

附:

矩阵大小:

Rond_Input2Cell =39*120

Pre_Rond_Input2Cell = 39*120

Y_FGate=1*120(行向量)

net_Cell=1*120(行向量)

Y_InGate =1*120(行向量)

tmp_input =1*39(行向量)

【问题讨论】:

  • 是 input2cell 和 net cell 类型的 cell 还是 matrix?
  • @Finn:这些是矩阵

标签: performance matlab for-loop vectorization


【解决方案1】:

您可以不使用for loop 而是使用bsxfun 来加速此计算,它使用内存来加速处理 下面的代码逐行执行相同的功能并添加它们

 Rond_Input2Cell = bsxfun(@times,tmp_input.' ,net_Cell.*Y_InGate) +  bsxfun(@times ,Pre_Rond_Input2Cell,Y_FGate);

解释:

Pre_Rond_Input2Cell(j,k)*Y_FGate(k)

这是通过使用 bsxfun(@times ,Pre_Rond_Input2Cell,Y_FGate) 执行的,它将 Pre_Rond_Input2Cell 的每 39 行与 Y_FGate 的 120 列相乘

net_Cell(k)*Y_InGate(k)*tmp_input(j)bsxfun(@times,tmp_input.' ,net_Cell.*Y_InGate) 替换,它将tmp_input 的每个元素与net_CellY_InGate 的点乘法相乘,最后存储在Rond_Input2Cell

这是一个性能检查

>> perform_check
Elapsed time is 0.000475 seconds.
Elapsed time is 0.000156 seconds.
>> perform_check
Elapsed time is 0.001089 seconds.
Elapsed time is 0.000288 seconds.

另一种方法是使用repmat

tic;
    Rond_Input2Cell =(Pre_Rond_Input2Cell.*repmat(Y_FGate,size(Pre_Rond_Input2Cell,1),1)) + (repmat(tmp_input.',1,size(Pre_Rond_Input2Cell,2)).*repmat(net_Cell.*Y_InGate,size(Pre_Rond_Input2Cell,1),1));
    toc;

这是一个带有 for 循环的性能测试

>> perf_test
Elapsed time is 0.003268 seconds.
Elapsed time is 0.001719 seconds.
>> perf_test
Elapsed time is 0.004211 seconds.
Elapsed time is 0.002348 seconds.
>> perf_test
Elapsed time is 0.002384 seconds.
Elapsed time is 0.000509 seconds.

Here 是 Loren 关于repmatbsxfun 的性能的文章

【讨论】:

  • 感谢您的回答,但是当我运行它时,它并不比 for 循环快多少,当我运行它时,经过的时间是 0.000125 秒,而 for 循环的经过时间是 0.000168 秒。请你指导我 bsxfun 做什么,有没有比 bsxfun 更快的方法
  • 你可以得到正确的时间如果你平均多次运行,bsxfun代表二进制单例扩展它使用内存来加速进程而不是迭代
  • 这里有 2 篇博客解释了 bsxfun 与 for 循环相比的性能blog.accelereyes.com/blog/2010/04/05/…
  • 现在我接受了这个答案,有什么办法可以接受你的答案吗?
【解决方案2】:

你的矢量化代码应该是这样的。

temp_mat = tmp_input' * (net_Cell .* Y_InGate) - 尺寸(39*120)

Rond_Input2Cell = (Pre_Rond_Input2Cell .* Y_FGate) .+ temp_mat - 尺寸(39*120)

【讨论】:

  • 感谢您的回答,但运行时出现错误“矩阵尺寸必须一致。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2014-05-16
  • 2011-11-22
相关资源
最近更新 更多