inporcd
inporcd

Reputation: 13

2D-3D array multiplication with numpy

I have two 2D (numpy) arrays from which I want to generate a 3D array in the following way: each of the n rows of the first array will multiply (elementwise) the second array to produce a new matrix, leading to n new arrays (forming a 3D array). I think a simple example will help to understand:

A = [[a11 a12 a13]
     [a21 a22 a23]]

B = [[b11 b12 b13]
     [b21 b22 b23]
     [b31 b32 b33]]

# The product "A*B" would result in a matrix C such as

C = [[[a11*b11  a12*b12  a13*b13]
      [a11*b21  a12*b22  a13*b23]
      [a11*b31  a12*b32  a13*b33]]

     [[a21*b11  a22*b12  a23*b13]
      [a21*b21  a22*b22  a23*b23]
      [a21*b31  a22*b32  a23*b33]]]

# Which is equivalent to (in numpy notation)

 C[0] = A[0]*B
 C[1] = A[1]*B

The fact is that the sizes are arbitrary (so not only 2x3 and 3x3, of course the second dimensions are always compatibles), I am looking for a solution without "for loops". I tried for example to repeat the array B then multiply

B = numpy.repeat(B[nu.newaxis,:,:],2,axis=0)
C = A*B

# operands could not be broadcast together with shapes (2,5) (2,3,5)

But the new dimensions are not compatibles.

Upvotes: 1

Views: 69

Answers (1)

kuzand
kuzand

Reputation: 9806

I think this is what you are looking for:

C = A[:, None] * B

Upvotes: 3

Related Questions