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?
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 .
You can multiply numpy arrays by scalars and it just works. This is also a very fast and efficient operation.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With