This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: NumPy recap and exercises

Solve linear equations

face Joe Stacey Josiah Wang

Another linear algebra question!

Challenge #2

Use NumPy and matrix multiplication to solve the following linear equations:

  • 2x_0 + 4x_1 = 8
  • 3x_0 - 2x_1 = 8

If you remember your linear algebra, then this is a matter of representing the equation in matrix form:

\begin{bmatrix}2 & 4\\3 & -2\end{bmatrix}\begin{bmatrix}x_0\\x_1\end{bmatrix}= \begin{bmatrix}8\\8\end{bmatrix}

Solving the equation is a matter of inverting the matrix with your coefficients.

\begin{bmatrix}x_0\\x_1\end{bmatrix}= \begin{bmatrix}2 & 4\\3 & -2\end{bmatrix}^{-1}\begin{bmatrix}8\\8\end{bmatrix}

See the documentation for np.linalg to find a function to compute the inverse of a matrix.

import numpy as np

a = np.array([[2, 4], [3, -2]])
b = np.array([8, 8])
x = ????
assert np.all(x == np.array([3. , 0.5]))

import numpy as np

a = np.array([[2, 4], [3, -2]])
b = np.array([8, 8])

x = np.linalg.inv(a) @ b

# or use np.matmul()
x = np.matmul(np.linalg.inv(a), b)