Multiplication of 1d arrays in numpy
Lets start with two arrays:
>>> aarray([0, 1, 2, 3, 4])>>> barray([5, 6, 7])
Transposing either array does not work because it is only 1D- there is nothing to transpose, instead you need to add a new axis:
>>> b.Tarray([5, 6, 7])>>> b[:,None]array([[5], [6], [7]])
To get the dot product to work as shown you would have to do something convoluted:
>>> np.dot(a[:,None],b[None,:])array([[ 0, 0, 0], [ 5, 6, 7], [10, 12, 14], [15, 18, 21], [20, 24, 28]])
You can rely on broadcasting instead of dot
:
a[:,None]*b
Or you can simply use outer:
np.outer(a,b)
All three options return the same result.
You might also be interested in something like this so that each vector is always a 2D array:
np.dot(np.atleast_2d(a).T, np.atleast_2d(b))
An even easier way is to define your array like this:
>>>b = numpy.array([[1,2,3]])
Then you can transpose your array easily:
>>>b.T array([[1], [2], [3]])
And you can also do the multiplication:
>>>b@b.T [[1 2 3] [2 4 6] [3 6 9]]
Another way is to force reshape your vector like this:
>>> b = numpy.array([1,2,3])>>> b.reshape(1,3).Tarray([[1], [2], [3]])