Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplication of 1d arrays in numpy

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.

like image 328
Cospel Avatar asked May 09 '14 13:05

Cospel


People also ask

How do you multiply the two NumPy arrays with each other?

multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.

How do you multiply two arrays together?

C = A . * B multiplies arrays A and B by multiplying corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

How do you perform matrix multiplication on the NumPy arrays A and B?

NumPy Multiplication Matrix If both a and b are 2-D (two dimensional) arrays -- Matrix multiplication. If either a or b is 0-D (also known as a scalar) -- Multiply by using numpy. multiply(a, b) or a * b. If a is an N-D array and b is a 1-D array -- Sum product over the last axis of a and b.


1 Answers

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))
like image 189
Daniel Avatar answered Sep 20 '22 06:09

Daniel