Matrix multiplication uses @ (Python 3.5+) or np.dot. For 2D arrays, A @ B computes standard matrix product; 1D cases follow inner-product rules.
2D matrix multiply
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A @ B)
Inner vs outer
np.dot(a, b)— inner product for 1D; matrix product for 2Dnp.matmul/@— strict linear algebra rulesnp.outer(a, b)— rank-1 outer product
Shape requirement
For (m, n) @ (n, p) inner dimensions must match. Mismatch raises clear ValueError—check shapes first.
Important interview questions and answers
- Q: A * B vs A @ B?
A: Star is element-wise; @ is matrix multiply (sum of products across inner axis). - Q: Why @ over np.dot?
A: @ is readable and preferred for matrix algebra in modern code.
Self-check
- Multiply 2×3 matrix by 3×2 matrix—result shape?
- Compute dot product of two 1D vectors.
Tip: Verify inner dimensions match before @.
Interview prep
- Shape rule?
(m,n) @ (n,p) → (m,p).
- outer?
Rank-1 outer product of two vectors.