numpy Linear algebra with np.linalg Solve linear systems with np.solve

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Consider the following three equations:

x0 + 2 * x1 + x2 = 4
         x1 + x2 = 3
x0 +          x2 = 5

We can express this system as a matrix equation A * x = b with:

A = np.array([[1, 2, 1],
              [0, 1, 1],
              [1, 0, 1]])
b = np.array([4, 3, 5])

Then, use np.linalg.solve to solve for x:

x = np.linalg.solve(A, b)
# Out: x = array([ 1.5, -0.5,  3.5])

A must be a square and full-rank matrix: All of its rows must be be linearly independent. A should be invertible/non-singular (its determinant is not zero). For example, If one row of A is a multiple of another, calling linalg.solve will raise LinAlgError: Singular matrix:

A = np.array([[1, 2, 1], 
              [2, 4, 2],   # Note that this row 2 * the first row
              [1, 0, 1]])
b = np.array([4,8,5])

Such systems can be solved with np.linalg.lstsq.



Got any numpy Question?