Numpy dot one matrix with an array of vectors and get a new array of vectors

Question:

Say we have an array of 2D vectors (describing a square shape), and a matrix (scale along y axis):

vecs = np.array([[1, 0],
                 [1, 1],
                 [0, 1],
                 [0, 0]])
mat = np.array([[1, 0],
                [0, 2]])

I want to get a new array of vectors, where each vector from vecs is dot multiplied with mat. Now I do it like this:

new_vecs = vecs.copy()
for i, vec in enumerate(vecs):
    new_vecs[i] = np.dot(mat, vec)

This produces the desired result:

>>> print(new_vecs)
[[1 0]
 [1 2]
 [0 2]
 [0 0]]

What are better ways to do this?

Asked By: grabantot

||

Answers:

The dot product np.dot will multiply matrices of any shape with each other, as long as their shapes line up: np.dot((a,b), (b,c)) -> (a,c). So if you invert the order, Numpy does this for you in one call:

In [3]: np.dot(vecs, mat)
Out[3]:
array([[1, 0],
       [1, 2],
       [0, 2],
       [0, 0]])
Answered By: Energya

You can use the following:

np.dot(mat , vecs.T).T
Answered By: syviad
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.