问题
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