Issue
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?
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.