Question

I have two 1d vectors(they can also be 2d matrices in some circumstances). I found the dot function for dot product but if i want to multiply a.dot(b) with these shapes:

a = [1,0.2,...]
a.shape = (10,)
b = [2.3,4,...]
b.shape = (21,)
a.dot(b) and I get ValueError: matrices not aligned.

and i want to do

c = a.dot(b)
c.shape = (10,21)

Any ideas how to do it? I tried also transpose function but it doesn't work.

Was it helpful?

Solution

Lets start with two arrays:

>>> a
array([0, 1, 2, 3, 4])
>>> b
array([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.T
array([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))

OTHER TIPS

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).T
array([[1],
       [2],
       [3]])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top