Numpy - scalar multiplication of a vector of a column vector

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

taking into account weight:

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

and vector of values:

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

As a result, I need a matrix that contains on each row a vector scalar of values multiplied by the value weights[row] :

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

One of the solutions I found:

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

Is there a better way?

+4
source share
2 answers

This operation is called an external agent . It can be done 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]]) 
+7
source

You can resize weights to an array of sizes (3.1) and then multiply it by values

 weights = numpy.array([1, 5, 2])[:,None] #column vector values = numpy.array([1, 3, 10, 4, 2]) result = weights*values print(result) array([[ 1, 3, 10, 4, 2], [ 5, 15, 50, 20, 10], [ 2, 6, 20, 8, 4]]) 

This answer explains [:,None]

+3
source

All Articles