简体   繁体   中英

How do you multiply a column vector with a row vector using @ in Python?

I'm running the following Python code:

import numpy as np
a=np.array([1,2])
b=np.array([3,4])
a@b #11
a.T@b #11
a@b.T #11
a.T@b.T #11

All four operations give the dot product. It was my understanding that a and b would be row vectors, so aT@b would give a 2x2 matrix. What am I misunderstanding here and how do I matrix multiply the column vector of a with the row vector of b ?

You can use np.outer to get the outer product

>>> import numpy as np
>>> a=np.array([1,2])
>>> b=np.array([3,4])
>>> np.outer(a, b)
array([[3, 4],
       [6, 8]])

You need to use two dimensional arrays to represent matrices/matrix multiplication.

a = np.array([[1, 2]])
b = np.array([[3, 4]])
print(a.T @ b)

What you can see here, is a property of how numpy arrays and matrices work.
You've created numpy arrays, each 2 long, which if you transpose, you still get an array of length 2. You can see this if you do a.shape . You have to create a 1x2 matrix, where it will work as you expected:

>>> a=np.array([[1,2]])
>>> b=np.array([[3,4]])
>>> a@b
Error
>>> a.T@b
array([[3, 4],
       [6, 8]])
>>> a@b.T
array([[11]])
>>> a.T@b.T
Error

First, it is important to understand that your a and b are neither rows nor columns. They are 1D.

Matrix multiplying them only works because the @ treats 1D operands specially. On the left they will be implicitly made a row, on the right a column. Dimensions added will be removed from the result. So a@b gives the inner product.

a@b
# 11

For the outer product, we need to build 2D vectors. A convenient way of transforming two 1D vectors into a column and a row is np.ix_ :

ac,br = np.ix_(a,b)

ac@br
# array([[3, 4],
#        [6, 8]])

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