Multiplication of 1d arrays in numpy

28,398

Solution 1

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))

Solution 2

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:

 >>>[email protected]
 [[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]])
Share:
28,398
Cospel
Author by

Cospel

Updated on March 12, 2020

Comments

  • Cospel
    Cospel about 4 years

    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.

  • Cospel
    Cospel almost 10 years
    I hope that it will be possible to just call simple .dot function because now i must distinguish the 1d vector and matrix.
  • Daniel
    Daniel almost 10 years
    @Cospel See my updated answer, it may be helpful for you. All it does is abstract away the if statements, but it can reduce your issue to a single line.
  • Solaxun
    Solaxun over 3 years
    That 3rd example is element-wise multiplication, not a dot product. Either the result should be [[14]], or the input should be >>>b*b.T