Use numpy to multiply a matrix by an array of points?

I have an array that contains a bunch of points (in particular, 3D vectors):

pts = np.array([ [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5], ]) 

And I would like to multiply each of these points by a transformation matrix:

 pts[0] = np.dot(transform_matrix, pts[0]) pts[1] = np.dot(transform_matrix, pts[1]) … pts[n] = np.dot(transform_matrix, pts[n]) 

How can I do this efficiently?

+5
source share
2 answers

I find this helps to write the einsum version einsum - after you see the indexes, you can often find out that there is a simpler version. For example, starting with

 >>> pts = np.random.random((5,3)) >>> transform_matrix = np.random.random((3,3)) >>> >>> pts_brute = pts.copy() >>> for i in range(len(pts_brute)): ... pts_brute[i] = transform_matrix.dot(pts_brute[i]) ... >>> pts_einsum = np.einsum("ij,kj->ik", pts, transform_matrix) >>> np.allclose(pts_brute, pts_einsum) True 

you can see that it's just

 >>> pts_dot = pts.dot(transform_matrix.T) >>> np.allclose(pts_brute, pts_dot) True 
+9
source

Matrix-matrix multiplication can be considered as “matrix vector multiplication” in batch mode, where each column in the second matrix is ​​one of the vectors multiplied by the first, and the result vectors are columns of the resulting matrix.

Note also that since (AB) T = B T A T and therefore (by transferring both sides) ((AB) T ) T = AB = (B T A T ) T, you can make a similar statement that the rows are the first the matrices are packet (left) multiplied by the transposition of the second matrix, and the result vectors are the rows of the matrix product.

+3
source

Source: https://habr.com/ru/post/1204383/


All Articles