Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy - scalar multiplication of column vector times row vector

What is the best and most efficient way to solve the following in python numpy:

given a weight vector:

weights = numpy.array([1, 5, 2])

and a value vector:

values = numpy.array([1, 3, 10, 4, 2])

as result I need a matrix, which contains on each row the values vector scalar multiplied with the value of weights[row]:

result = [
    [1,  3, 10,  4,  2],
    [5, 15, 50, 20, 10],
    [2,  6, 20,  8,  4]
]

One solution which I found is the following:

result = numpy.array([ weights[n]*values for n in range(len(weights)) ])

Is there a better way?

like image 488
Stefan Profanter Avatar asked Apr 12 '13 12:04

Stefan Profanter


People also ask

Can you multiply a column vector by a row vector?

To multiply a row vector by a column vector, the row vector must have as many columns as the column vector has rows. Let us define the multiplication between a matrix A and a vector x in which the number of columns in A equals the number of rows in x .

Can you multiply a NumPy array by a scalar?

You can multiply numpy arrays by scalars and it just works. This is also a very fast and efficient operation.


1 Answers

This operation is called the outer product. It can be performed using numpy.outer():

In [6]: numpy.outer(weights, values)
Out[6]: 
array([[ 1,  3, 10,  4,  2],
       [ 5, 15, 50, 20, 10],
       [ 2,  6, 20,  8,  4]])
like image 51
NPE Avatar answered Nov 15 '22 01:11

NPE