As noted below, if using python3.5+ and numpy v1.10+, the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have multiple 2D arrays to dot
together, you may consider the np.linalg.multi_dot
function, which simplifies the syntax of many nested np.dot
s. Note that this only works with 2D arrays (i.e. not for matrix-vector multiplication).
>>> np.dot(np.dot(a, a.T), a).dot(a.T)
array([[1406, 382, 446],
[ 382, 106, 126],
[ 446, 126, 152]])
>>> np.linalg.multi_dot((a, a.T, a, a.T))
array([[1406, 382, 446],
[ 382, 106, 126],
[ 446, 126, 152]])