3

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?

Kris
  • 22,079
  • 3
  • 30
  • 35

1 Answers1

3

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]))
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Could you maybe elaborate on permuting a 2D array with a 3D permutation vector? – Kris Nov 09 '14 at 18:40
  • @Kris If you are talking about permutation matrix, that's a different ball-game. Think of permute in this case as more of a reshaping thing. So, with `permute(B,[3 1 2])`, I am making columns of it as rows and the rows as the slices in 3D. After that, with `bsxfun(@times..)`, the expansion of elements takes place to cover for the singleton dimensions for both `A` and the shifted version of B and finally the elementwise multiplication. Hope this makes sense? Looking into the linked documentations of these two functions should make it more clear. – Divakar Nov 09 '14 at 18:45
  • 1
    @Kris Here's one very closely related one - http://stackoverflow.com/questions/23807960/bsxfun-implementation-in-matrix-multiplication/23808285#23808285 , might be worth a look! – Divakar Nov 09 '14 at 18:50