* versus @
import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(A * B) print(A @ B)
Write Python. Understand every error.
NumPy · topic 24 of 25
A 1D array can represent a vector and a 2D array a matrix. Be careful to choose the right kind of multiplication:
A * B multiplies element by element; the shapes must match or broadcastA @ B (or np.dot(A, B)) is the matrix product from mathematicsFor a matrix product the inner sizes must agree: a (n, k) matrix times a (k, m) matrix gives a (n, m) result. Each result element is a row of A combined with a column of B: multiply the pairs and add them up.
A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(A @ B) # [[19 22] # [43 50]] because 1*5 + 2*7 = 19, and so on
The dot product of two vectors, u @ v, multiplies matching elements and adds them, giving one number. Multiplying a matrix by a vector gives a vector, which is a neat way to compute many weighted totals at once.
The np.linalg module solves common problems. np.linalg.solve(A, b) finds x in the system A @ x = b, np.linalg.det(A) gives the determinant, and np.linalg.inv(A) the inverse. np.eye(n) is the identity matrix, and A.T the transpose.
# 2x + y = 5 # x + 3y = 10 A = np.array([[2, 1], [1, 3]]) b = np.array([5, 10]) print(np.linalg.solve(A, b)) # [1. 3.]
A * B multiplies matching elements, while A @ B (or np.dot(A, B)) is the matrix product from mathematics.np.linalg.det gives the determinant and np.linalg.inv gives the inverse.* when the matrix product is needed.
import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(A * B) print(A @ B)
import numpy as np marks = np.array([80, 70, 90]) weights = np.array([0.5, 0.3, 0.2]) print(marks @ weights) # weighted average
import numpy as np # rows: shops, columns: tea, samosa, biscuit qty = np.array([[10, 4, 6], [3, 8, 2]]) price = np.array([10, 15, 5]) print(qty @ price) # bill for each shop
import numpy as np # 2x + y = 5 # x + 3y = 10 A = np.array([[2, 1], [1, 3]]) b = np.array([5, 10]) print(np.linalg.solve(A, b)) print(np.linalg.det(A))
import numpy as np A = np.array([[4, 7], [2, 6]]) Ainv = np.linalg.inv(A) print(np.round(Ainv, 2)) print(np.round(A @ Ainv, 2))
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
import numpy as np a = np.array([[1, 2], [3, 4]]) b = np.array([[1, 0], [0, 1]]) print(a @ b)
Multiplying by the identity matrix leaves a matrix unchanged.
import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) print(a @ b)
For two 1D arrays, @ is the dot product: 4 + 10 + 18 = 32.
import numpy as np print(round(np.linalg.det(np.array([[2, 1], [1, 3]])), 2))
det = 2×3 − 1×1 = 5.
a * b and a @ b for two matrices?Use @ (or np.dot) for real matrix multiplication.
import numpy as np a = np.array([[2, 0], [0, 4]]) print(np.linalg.inv(a))
The inverse of a diagonal matrix has 1/2 and 1/4 on the diagonal.