Matrix Inverse by Gauss-Jordan Elimination

Linear AlgebraMedium+15 XP+15

Matrix Inverse by Gauss-Jordan Elimination

The inverse of a matrix A is the matrix that undoes it: multiply the two together and you get the identity back. It's the closest thing matrices have to division, and it's the engine behind the normal equation that fits a linear regression.

The standard way to find it by hand is Gauss-Jordan elimination: write A next to the identity matrix, then row-reduce the left half into the identity. Whatever the right half turns into is the inverse.

Task: write inverse(matrix) returning the inverse, every entry rounded to 4 decimal places.

The procedure, column by column:

  1. Glue the identity matrix onto the right of A, giving n rows of 2n numbers.
  2. For column c, pick the row at or below c with the largest absolute value in that column, and swap it up into position c. (This is called partial pivoting. Even when any non-zero row would do algebraically, picking the biggest keeps the division from amplifying rounding error.)
  3. Divide that whole row by its own entry in column c, making the pivot exactly 1.
  4. For every other row, subtract a multiple of the pivot row so its entry in column c becomes 0.
  5. Move to the next column.

When you're done, the left half is the identity and the right half is your answer.

  • matrix is square and always invertible, so you never hit a column of zeros.
  • Return only the right half — n rows of n numbers.
  • NumPy is available if you want it, but doing the elimination by hand is the point.

Examples

matrix = [[4, 7], [2, 6]]
returns [[0.6, -0.7], [-0.2, 0.4]]
matrix = [[1, 0], [0, 1]]
returns [[1.0, 0.0], [0.0, 1.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run