Matrix vector multiplication

When I multiply two numpy arrays of sizes (nxn) * (nx 1), I get a matrix of size (nxn). Following the rules of normal matrix multiplication, a vector (nx 1) is expected, but I just can't find any information on how to do this in the Python Numpy module.

The fact is that I do not want to implement it manually in order to maintain the speed of the program.

A sample code is shown below:

a = np.array([[ 5, 1 ,3], [ 1, 1 ,1], [ 1, 2 ,1]]) b = np.array([1, 2, 3]) print a*b >> [[5 2 9] [1 2 3] [1 4 3]] 

I want to:

 print a*b >> [16 6 8] 
+80
python arrays numpy vector matrix
Feb 04 '14 at 20:43
source share
1 answer

Simplest solution

Use numpy.dot or a.dot(b) . See the documentation here .

 >>> a = np.array([[ 5, 1 ,3], [ 1, 1 ,1], [ 1, 2 ,1]]) >>> b = np.array([1, 2, 3]) >>> print a.dot(b) array([16, 6, 8]) 

This is because numpy arrays are not matrices, and standard *, +, -, / operations work on an array on arrays. Instead, you can try using numpy.matrix , and * will be considered as matrix multiplication.




Other solutions

It is also known that there are other options:

  • As indicated below, when using python3.5 +, the @ operator works as you expected:

     >>> print(a @ b) array([16, 6, 8]) 
  • If you want overkill, you can use numpy.einsum . The documentation will give you a taste for how this works, but to be honest, I didn't quite understand how to use it until I read this answer and just play 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 experimental numpy.matmul , which works like numpy.dot with two main exceptions: there is no scalar multiplication, but it works with matrix stacks.

     >>> np.matmul(a, b) array([16, 6, 8]) 



More rare options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1 :

     >>> np.tensordot(a, b, axes=1) array([16, 6, 8]) 
  • Do not use numpy.vdot if you have a matrix of complex numbers, since the matrix will be flattened to a 1D array, then it will try to find the complex conjugate point product between your flattened matrix and the vector (which will not be done due to size mismatch n*m vs n ).

+111
Feb 04 '14 at 20:46
source share



All Articles