简体   繁体   中英

matrix - vector multiplication in python (numpy)

I have one vector (shape (4,1)) and one matrix (shape (4,4))

I am trying to multiply them using the * operator which when used on a matrix object is matrix multiplication, but I am getting a value error:

ValueError: shapes (4,1) and (4,4) not aligned: 1 (dim 1) != 4 (dim 0)

How do I go about this? I understand how to do this by hand and thought it would be fairly simple with numpy

You cannot multiply a 4x1 vector with a 4x4 matrix.

You should do the opposite, multiply the matrix with the vector. Or transpose the vector.

Remember that for a matrix multiplication, the second dimension of the first matrix must be equal to the first dimension of the second one. Therefore, performing a matrix multiplication of a 4x1 vector and a 4x4 matrix is not possible.

What you can do is transpose the vector (using myvector.T ) so you get a 1x4 vector and multiply that with your 4x4 matrix.

Alternatively, you could multiply the vector on the right side.

>>> v1 = numpy.arange(1,5).reshape(1,4)
>>> v1
array([[1, 2, 3, 4]])
>>> v1.shape
(1, 4)
>>> v2 = numpy.ones((4,4))
>>> v2
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
>>> v2.shape
(4, 4)
>>> v3 = v1*v2
>>> v3
array([[ 1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.]])
>>> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM