I've got an array which contains a bunch of points (3D vectors, specifically):
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 one of those 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?
To multiply two matrices use the dot() function of NumPy. It takes only 2 arguments and returns the product of two matrices.
Method 1: Multiply NumPy array by a scalar using the * operator. The first method to multiply the NumPy array is the use of the ' * ' operator. It will directly multiply all the elements of the NumPy array whether it is a Single Dimensional or Multi-Dimensional array.
multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.
If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred. If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
I find it helps to write the einsum
version first-- after you see the indices you can often recognize that there's a simpler version. For example, starting from
>>> 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 this is simply
>>> pts_dot = pts.dot(transform_matrix.T)
>>> np.allclose(pts_brute, pts_dot)
True
Matrix-matrix multiplication can be thought of as "batch-mode" matrix-vector multiplication, where each column in the second matrix is one of the vectors being multiplied by the first, with the result vectors being the columns of the resulting matrix.
Also note that since (AB)T = BTAT, and therefore (by transposing both sides) ((AB)T)T = AB = (BTAT)T you can make a similar statement about the rows of the first matrix being batch-(left-)multiplied by the transpose of the second matrix, with the result vectors being the rows of the matrix product.
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