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.
CodePudding user response:
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)
CodePudding user response:
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)