MATLAB: multiplication by elements of two matrices over the same index?

I'm trying to figure out if there is a native way to get a certain type of elemental product of two matrices in Matlab.

The product I'm looking for takes two matrices, A

and B

, and returns there a product C

whose elements are given

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

      

Naturally, the number of columns A

is considered the same as the number of rows B

.

Right now, I am 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 the elementwise multiplication with:

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

      

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

+3


source to share


1 answer


You need to "shift" the first two dimensions B in the second and third dimensions respectively with , and then use with the option to work on and the offset dimensional version - permute

bsxfun

@times

A

B



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

      

+3


source







All Articles