Kris
Kris

Reputation: 23599

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

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?

Upvotes: 3

Views: 591

Answers (1)

Divakar
Divakar

Reputation: 221664

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]))

Upvotes: 3

Related Questions