本文介绍了向量化Triple For循环的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在尝试通过此三重循环构建矩阵Alpha:

Currently, I am trying to build the matrix Alpha through this triple-loop:

Alpha = zeros(a_length, b_length);
for a = 1:a_length
  for b = 1:b_length
      for c = 1:c_length
          Alpha(a,b) = Alpha(a,b) + Beta(c,a) * Gamma(b,c);
      end
  end
end

有没有办法将两个向量传递给Beta和Gamma矩阵,这样我就可以在一条简单的矢量化的优雅代码行中构造整个Alpha?

Is there a way to pass in two vectors to the Beta and Gamma Matrices, such that I can construct the entirety of Alpha in a single, vectorized line of elegant code?

推荐答案

您可以使用简单的matrix multiplication进行救援-

You could use simple matrix multiplication to your rescue -

Alpha = (Gamma*Beta).'

或者这样-

Alpha = Beta.'*Gamma.'

或者是一些基于bsxfun的复杂方法-

Or a bit complicated bsxfun based approach -

Alpha = sum(bsxfun(@times,permute(Gamma,[3 1 2]),permute(Beta,[2 3 1])),3)

如果您想避免使用较早的bsxfun方法中的一个permute-

And if you want to avoid one permute from the earlier bsxfun approach -

Alpha = squeeze(sum(bsxfun(@times,Gamma,permute(Beta,[3 1 2])),2)).'

或者这个-

Alpha = squeeze(sum(bsxfun(@times,Beta.',permute(Gamma,[3 2 1])),2))

这篇关于向量化Triple For循环的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 10:08