1

I have a matrix A of zise MxN, and vector b of size L. how can I create a matrix C of size MxNxL such that:

C[m, n, k] = A[m, n] * b[k]

pretty much the same as dot product of two vectors to create 2D matrix, but with one dimention higher.

I had tried some variations of a dot product but I couldnt find it.

starball
  • 20,030
  • 7
  • 43
  • 238
  • Please provide enough code so others can better understand or reproduce the problem. – Community Jan 02 '23 at 22:56
  • 1
    So, not at all like dot product. Dot product usually contain a Σ somewhere. This looks more like a scalar product with some broadcasting. – chrslg Jan 02 '23 at 23:14
  • I think the fuction you're looking at is outer : https://numpy.org/doc/stable/reference/generated/numpy.outer.html – Miguel Jan 03 '23 at 12:07

2 Answers2

1

You don't want a dot product (sum of the product over an axis), but a simple product that creates a new dimension.

Use broadcasting:

C = A[..., None] * b

Example:

A = np.ones((2,3))
b = np.ones(4)

C = A[..., None] * b

C.shape
# (2, 3, 4)
mozway
  • 194,879
  • 13
  • 39
  • 75
0

The most intuitive way to solve your problem is using np.einsum. It follows the maths equation you wrote in the question itself.

A = np.ones((2,3))
b = np.ones(4)

C = np.einsum('ij, k -> ijk', A,b)
C.shape
# (2, 3, 4)
MSS
  • 3,306
  • 1
  • 19
  • 50