Dot product between matrix and 1d array in numpy

I need to do dot product of two matrices in numpy. However, one of them actually has the same meaning on every line. Something like:

array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2]])

      

For optimization purposes, I only store one column as a 1d array.

Is there a way to calculate the dot product between this and a normal 2d matrix without to explicitly create the above matrix?

+3


source to share


2 answers


if you have an array:

a = np.array([0, 1, 2])

      

which is a matrix like:

>>> np.repeat(a[:,np.newaxis], 5, 1)
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2]])

      



and you need a dot product with matrix m:

m = np.arange(5*4).reshape(5,4)

      

you can use:

a[:,np.newaxis] * np.sum(m, axis=0)

      

+3


source


When you execute the dot product of two arrays, you compute the product of the dots of every row of the first array with every column of the second. If your matrix-one-in-a-in-vector (MTFIAV) is the first operand of the dot product, it is easy to see that you can specify a duplicate value from the dot product and do one multiplication with the result of summing each column of the second array:

>>> a = np.arange(3)
>>> a
array([0, 1, 2])
>>> aa = np.repeat(a, 5).reshape(len(a), -1)
>>> aa
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2]])

>>> np.dot(aa, b)
array([[  0,   0,   0,   0],
       [ 40,  45,  50,  55],
       [ 80,  90, 100, 110]])
>>> np.outer(a, b.sum(axis=0))
array([[  0,   0,   0,   0],
       [ 40,  45,  50,  55],
       [ 80,  90, 100, 110]])

      



If your MTFIAV is the second operand, it’s not hard to see that the result is also MTFIAV, and that its vector representation can be obtained by computing the dot product of the first operand with a vector:

>>> c = np.arange(12).reshape(4, 3)

>>> np.dot(c, aa)
array([[ 5,  5,  5,  5,  5],
       [14, 14, 14, 14, 14],
       [23, 23, 23, 23, 23],
       [32, 32, 32, 32, 32]])
>>> np.dot(c, a)
array([ 5, 14, 23, 32])

      

+4


source







All Articles