Numerical weight and total rows of the matrix

Using Python and Numpy, I would like to:

  • Consider each row (n columns x m rows) a matrix as a vector
  • Weight of each line (scalar multiplication by each component vector)
  • Add each line to create the final vector (adding a vector).

The weights are specified in the regular numpy array, nx 1, so each vector m in the matrix must be multiplied by the weight n.

Here is what I have (with test data, the actual matrix is ​​huge), which is possibly very non-Numpy and non-Pythonic. Can anyone better? Thank!

import numpy

# test data
mvec1 = numpy.array([1,2,3])
mvec2 = numpy.array([4,5,6])
start_matrix = numpy.matrix([mvec1,mvec2])
weights = numpy.array([0.5,-1])

#computation
wmatrix = [ weights[n]*start_matrix[n] for n in range(len(weights)) ]

vector_answer = [0,0,0]
for x in wmatrix: vector_answer+=x
+5
source share
2 answers

Even the “technically” correct answer was ready, I will give my simple answer:

from numpy import array, dot
dot(array([0.5, -1]), array([[1, 2, 3], [4, 5, 6]]))
# array([-3.5 -4. -4.5])

( ).

Update: , , (10-15) , !

+8

numpy.array, a numpy.matrix.

start_matrix = numpy.array([[1,2,3],[4,5,6]])
weights = numpy.array([0.5,-1])
final_vector = (start_matrix.T * weights).sum(axis=1)
# array([-3.5, -4. , -4.5])

* - NumPy.

+8

All Articles