Advanced Linear Algebra & Advanced Patterns Matrix operations, sorting/searching, and the tricks that come up in real code.
import numpy as np
A = np .array([[2.0 , 0.0 ], [0.0 , 2.0 ]])
print (np .linalg.det(A)) # determinant -> 4.0
print (np .linalg.inv(A)) # inverse
print (np .linalg.solve(A, np .array([4.0 , 6.0 ]))) # solve Ax = b
▶ Run
Function What it finds Example np.sort(a)
sorted copy
np.sort([3,1,2]) → array([1, 2, 3])
a.argsort()
indices that would sort the array
array([3,1,2]).argsort() → array([1, 2, 0])
np.unique(a, return_counts=True)
distinct values + how often each appears
np.unique([1,1,2]) → (array([1, 2]), array([2, 1]))
np.where(cond) / np.argwhere(cond)
coordinates where a condition holds
np.where([1,-1,2] > 0) → (array([0, 2]),)
np.searchsorted(a, v)
insertion point to keep a sorted array sorted
np.searchsorted([1,3,5], 4) → 2
import numpy as np
X = np .array([[3 , 0 ], [1 , 0 ], [2 , 0 ]])
order = np .argsort(X[:, 0 ])
print (X[order]) # rows sorted by column 0, without touching column 1
vals, counts = np .unique([3 , 1 , 2 , 3 , 3 , 1 ], return_counts=True )
print (vals, counts) # [1 2 3] [2 1 3]
▶ Run
⚠️ Watch out: np.reshape and matrix transpose are NOT the same operation: a frequent source of silent bugs when porting math notation into code. Reshape relabels the flat buffer; transpose actually reorders it.
Now practice it Exercises that use what this lesson just covered.