Python/Numpy - Matrix Multiply a 2D Array and Each Row of another 2D Array

dot-product, numpy, python

Solution

This gives (what looks to me like) the correct result:

numpy.dot(b, a.T)

Here's some example output:

>>> a = numpy.arange(9).reshape(3, 3)
>>> b = numpy.arange(60).reshape(20, 3)
>>> numpy.dot(b, a.T)
array([[   5,   14,   23],
       [  14,   50,   86],
       [  23,   86,  149],
       [  32,  122,  212],
       ....

Problem

What is the best way to do this? ``` a = 3x3 array b = 20x3 array c = 20x3 array = some_dot_function(a, b) where: c[0] = np.dot(a, b[0]) c[1] = np.dot(a, b[1]) c[2] = np.dot(a, b[2]) ...etc... ``` I know this can be done with a simple python loop or using numpy's apply_along_axis, but I'm wondering if there is any good way to do this entirely within the underlying C code of numpy. I looked at tensordot and some other functions, but didn't have any luck. I also tried the following: ``` c = np.dot(a, b[:, :, np.newaxis] #c.shape = (3, 59, 1) ``` This actually ran and gave results that looked approximately right, except that the resulting array is not 20x3. I may be able to find a way to reshape it into the array I want, but I figured that there must be an easier/cleaner/clearer built-in method that I'm missing?

Original source