import numpy as np
a = np.array([[1,2],[3,4]])
print(a.shape)
c = np.array([[1,2,3]])
print(c.shape)
#wanted result multiplication of a*c would return 2,2,3 shape matrix
final = np.array([[[1,2,3],[2,4,6]],[[3,6,9],[4,8,12]]])
print(final.shape)
print(final)
I would like to multiply two matrices with different shapes and basically get a result which would be a 3d matrix. I hope you get the pattern from the code. Is there any simple numpyic way for this? I would appreciate it.
You can use NumPy broadcasting for this:
a[...,None] * c
array([[[ 1, 2, 3],
[ 2, 4, 6]],
[[ 3, 6, 9],
[ 4, 8, 12]]])
The following basically alings the dimensions so the multiplication is broadcast to the desired output shape:
a[...,None].shape
(2, 2, 1)
Try np.einsum
out = np.einsum('ij,kl->klj',c,a)
Out[35]:
array([[[ 1, 2, 3],
[ 2, 4, 6]],
[[ 3, 6, 9],
[ 4, 8, 12]]])
In [36]: out.shape
Out[36]: (2, 2, 3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.