MATLAB: element-wise multiplication of two matrices over one index?

假如想象 提交于 2019-12-10 19:49:37

问题


I'm trying to figure out if there's a native way of obtaining a certain kind of element-wise product of two matrices in Matlab.

The product that I'm looking for takes two matrices, A and B say, and returns there product C, whose elements are given by

C(i,j,k) = A(i,j)*B(j,k)

Naturally, the number of columns of A is assumed be the same as the number of rows of B.

Right now, I'm using the following for-loop (assuming size(A,2)==size(B,1) is true). First, I initialize C:

C = zeros(size(A,1), size(A,2), size(B,2));

And then I perform element-wise multiplication via:

for i=1:size(A,2)
    C(:,i,:) = A(:,i)*B(i,:);
end

So, my question is: Is there a native way to this sort of thing in Matlab?


回答1:


You need to "shift" the first two dimensions of B into second and third dimensions respectively with permute and then use bsxfun with @times option to operate on A and the shifted dimension version of B -

C = bsxfun(@times,A,permute(B,[3 1 2]))


来源:https://stackoverflow.com/questions/26831564/matlab-element-wise-multiplication-of-two-matrices-over-one-index

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