Yes! In NumPy, there are multiple ways to perform matrix multiplication, and the @ operator is just one of them (introduced in Python 3.5+ with PEP 465). Here are all the common methods:
1. @ Operator (Recommended for clarity)
C = A @ B # Applies B after A (A *then* B)
- Best for readability (Python ≥3.5).
- Works identically to
np.matmul().
2. np.matmul() (Explicit function)
C = np.matmul(A, B) # Equivalent to A @ B
- Same as
@ but more explicit.
- Handles broadcasting for batches of matrices.
3. np.dot() (General dot product)
C = np.dot(A, B) # Also works, but less explicit for matrices
- Works for 2D matrices, but behavior differs for higher dimensions.
- For 2D arrays,
np.dot(A, B) is equivalent to A @ B.
4. np.einsum() (Einstein summation, flexible but complex)
C = np.einsum('ij,jk->ik', A, B) # Explicit indices
- Overkill for simple matrix multiplication but powerful for custom operations.
5. * + np.sum() (Element-wise + sum, not recommended)
C = (A[:, :, None] * B[None, :, :]).sum(axis=1) # Hacky way
- Avoid this—it’s inefficient and harder to read.
Key Differences:
| Method | Syntax | Notes |
|---|
@ | A @ B | Cleanest, Python ≥3.5. |
np.matmul | matmul(A,B) | Same as @, but explicit. Handles broadcasting. |
np.dot | dot(A,B) | Works but avoid for clarity (behavior differs for non-2D arrays). |
np.einsum | einsum(...) | Flexible but verbose. |
Example with Affine Transforms (A then B)
import numpy as np
# Two 3x3 affine matrices (e.g., from skimage.transform)
A = np.array([[1, 0, 5], [0, 1, 10], [0, 0, 1]]) # Translate by (5, 10)
B = np.array([[2, 0, 0], [0, 2, 0], [0, 0, 1]]) # Scale by 2
# Combine transforms (A first, then B)
C1 = B @ A # Preferred (Python 3.5+)
C2 = np.matmul(B, A) # Explicit
C3 = np.dot(B, A) # Also works (but less clear)
assert np.allclose(C1, C2) and np.allclose(C2, C3)
Recommendation:
- Use
@ if you’re on Python ≥3.5 (most readable).
- Use
np.matmul() if you need compatibility or broadcasting.
- Avoid
np.dot() for matrix multiplication unless you’re working with older code.
Let me know if you’d like a deeper dive into any of these!