Vectorizing the Sum of a Triple For Loop

北战南征 提交于 2019-12-24 12:14:21

问题


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

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?


回答1:


You could use simple matrix multiplication to your rescue -

Alpha = (Gamma*Beta).'

Or this way -

Alpha = Beta.'*Gamma.'

Or a bit complicated bsxfun based approach -

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

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)).'

Or this -

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


来源:https://stackoverflow.com/questions/27142201/vectorizing-the-sum-of-a-triple-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!