TExcelTAD
Home › Linear Algebra & Matrix Theory › Gaussian Elimination

Gaussian Elimination

Gaussian elimination is the systematic way to apply elementary row operations until a system is in echelon form, a staircase shape that can be solved from the bottom up. It decides whether a system has zero, one or infinitely many solutions, and in this lesson you implement it yourself.

Echelon form

A matrix is in row echelon form when:

  1. all zero rows are at the bottom, and
  2. the first non-zero entry of each row (its pivot, or leading entry) is strictly to the right of the pivot in the row above.
[21−13042000510]pivots: 2 (column 1), 4 (column 2), 5 (column 3)every entry below a pivot is 0\left[\begin{array}{rrr|r} 2 & 1 & -1 & 3 \\ 0 & 4 & 2 & 0 \\ 0 & 0 & 5 & 10 \end{array}\right] \qquad \begin{aligned} &\text{pivots: } 2 \text{ (column 1)},\ 4 \text{ (column 2)},\ 5 \text{ (column 3)} \\ &\text{every entry below a pivot is } 0 \end{aligned}

The columns that contain a pivot are pivot columns; their variables are pivot variables (or leading variables). The other variables are free.

The algorithm

Work column by column, from left to right:

  1. Find a row, at or below the current row, with a non-zero entry in this column. If there is none, move on to the next column (this variable will be free).
  2. Swap that row into the current position. Its entry is the pivot.
  3. For every row below, add a multiple of the pivot row that makes the entry under the pivot 0: Ri←Ri−(ai/pivot)⋅RcurrentR_i \leftarrow R_i - (a_i / \text{pivot}) \cdot R_{\text{current}}.
  4. Move one row down and one column right, and repeat.

Then read off the result:

  • A row [0 0 … 0∣c][0\ 0\ \ldots\ 0 \mid c] with c≠0c \ne 0 says 0=c0 = c: the system is inconsistent.
  • Otherwise it is consistent. If every variable column has a pivot, the solution is unique; if some variable is free, there are infinitely many solutions.
  • Solve by back substitution: the last equation first, then work upwards.

A worked example

x+2y+z=42x+5y+3z=11−x+y+4z=10[121425311−11410]\begin{aligned} x + 2y + z &= 4 \\ 2x + 5y + 3z &= 11 \\ -x + y + 4z &= 10 \end{aligned} \qquad \left[\begin{array}{rrr|r} 1 & 2 & 1 & 4 \\ 2 & 5 & 3 & 11 \\ -1 & 1 & 4 & 10 \end{array}\right]
→R2←R2−2R1, R3←R3+R1[1214011303514]→R3←R3−3R2[121401130025]\xrightarrow{R_2 \leftarrow R_2 - 2R_1,\ R_3 \leftarrow R_3 + R_1} \left[\begin{array}{rrr|r} 1 & 2 & 1 & 4 \\ 0 & 1 & 1 & 3 \\ 0 & 3 & 5 & 14 \end{array}\right] \xrightarrow{R_3 \leftarrow R_3 - 3R_2} \left[\begin{array}{rrr|r} 1 & 2 & 1 & 4 \\ 0 & 1 & 1 & 3 \\ 0 & 0 & 2 & 5 \end{array}\right]
Back substitution: 2z=5→z=52y+z=3→y=12x+2y+z=4→x=4−1−52=12\begin{aligned} &\text{Back substitution: } & 2z &= 5 \to z = \frac{5}{2} \\ & & y + z &= 3 \to y = \frac{1}{2} \\ & & x + 2y + z &= 4 \to x = 4 - 1 - \frac{5}{2} = \frac{1}{2} \end{aligned}

Implementing it with Fractions

python · try it yourself
from fractions import Fraction as F

def echelon(M):
    """Forward elimination. Returns (echelon matrix, list of pivot columns)."""
    M = [[F(a) for a in row] for row in M]
    rows, cols = len(M), len(M[0]) - 1      # last column is the right-hand side
    pivots, r = [], 0
    for c in range(cols):
        p = next((i for i in range(r, rows) if M[i][c] != 0), None)
        if p is None:
            continue                          # no pivot here: free variable
        M[r], M[p] = M[p], M[r]
        for i in range(r + 1, rows):
            f = M[i][c] / M[r][c]
            M[i] = [a - f * b for a, b in zip(M[i], M[r])]
        pivots.append(c)
        r += 1
        if r == rows:
            break
    return M, pivots

def back_substitute(M, pivots):
    n = len(M[0]) - 1
    if any(all(a == 0 for a in row[:-1]) and row[-1] != 0 for row in M):
        return "inconsistent"
    if len(pivots) < n:
        return "infinitely many solutions"
    x = [F(0)] * n
    for r in reversed(range(n)):
        s = sum(M[r][j] * x[j] for j in range(r + 1, n))
        x[r] = (M[r][-1] - s) / M[r][r]
    return x

A = [[1, 2, 1, 4], [2, 5, 3, 11], [-1, 1, 4, 10]]
E, piv = echelon(A)
for row in E:
    print([str(a) for a in row])
print("pivot columns:", piv)
print("solution:", [str(v) for v in back_substitute(E, piv)])
['1', '2', '1', '4']
['0', '1', '1', '3']
['0', '0', '2', '5']
pivot columns: [0, 1, 2]
solution: ['1/2', '1/2', '5/2']

The code takes the first non-zero entry as pivot. That is fine with exact fractions; with floating point you would pick the entry of largest absolute value instead (partial pivoting), which keeps rounding errors small.

Comparing with SymPy

SymPy gives the same answer. Its echelon_form() may scale rows differently, since echelon form is not unique (only the reduced form is, see Uniqueness of the Reduced Echelon Form), but the pivot positions and the solution agree:

python · try it yourself
from sympy import Matrix

aug = Matrix([[1, 2, 1, 4], [2, 5, 3, 11], [-1, 1, 4, 10]])
print(aug.echelon_form().tolist())
print("solution:", list(aug[:, :3].solve(aug[:, 3])))

# an inconsistent system: the last row becomes 0 0 0 | nonzero
bad = Matrix([[1, 1, 2, 3], [2, 3, 1, 5], [3, 4, 3, 9]])
print(bad.echelon_form().tolist())
[[1, 2, 1, 4], [0, 1, 1, 3], [0, 0, 2, 5]]
solution: [1/2, 1/2, 5/2]
[[1, 1, 2, 3], [0, 1, -3, -1], [0, 0, 0, 1]]

In the second system R3=R1+R2R_3 = R_1 + R_2 on the left-hand side, but 3+5≠93 + 5 \ne 9 on the right, so elimination produces 0=10 = 1.

In software

Gaussian elimination costs about 23⋅n3\frac{2}{3} \cdot n^3 arithmetic operations for nn equations. That cubic growth is why big problems (millions of unknowns in physics simulations or finite element models) use sparse or iterative methods instead. For dense matrices, numpy.linalg.solve calls LAPACK's LU factorization with partial pivoting, which is Gaussian elimination with bookkeeping. See Numerical Linear Algebra.

Exercises

Exercise 1: Echelon or not?

Which are in row echelon form? (a) [130002000]\begin{bmatrix} 1 & 3 & 0 \\ 0 & 0 & 2 \\ 0 & 0 & 0 \end{bmatrix} (b) [012103]\begin{bmatrix} 0 & 1 & 2 \\ 1 & 0 & 3 \end{bmatrix} (c) [211000004]\begin{bmatrix} 2 & 1 & 1 \\ 0 & 0 & 0 \\ 0 & 0 & 4 \end{bmatrix}.

Answer

Only (a).

Solution

(b) the pivot of row 2 (column 1) is left of the pivot of row 1 (column 2). (c) has a zero row above a non-zero row.

Exercise 2: Eliminate by hand

Solve x−y+z=2x - y + z = 2, 2x+y−z=12x + y - z = 1, x+2y+3z=14x + 2y + 3z = 14 by Gaussian elimination.

Answer

x=1x = 1, y=2y = 2, z=3z = 3.

Solution
[1−11221−1112314]→R3−R1R2−2R1[1−11203−3−303212]→R3−R2[1−11203−3−300515]\left[\begin{array}{rrr|r} 1 & -1 & 1 & 2 \\ 2 & 1 & -1 & 1 \\ 1 & 2 & 3 & 14 \end{array}\right] \xrightarrow[R_3 - R_1]{R_2 - 2R_1} \left[\begin{array}{rrr|r} 1 & -1 & 1 & 2 \\ 0 & 3 & -3 & -3 \\ 0 & 3 & 2 & 12 \end{array}\right] \xrightarrow{R_3 - R_2} \left[\begin{array}{rrr|r} 1 & -1 & 1 & 2 \\ 0 & 3 & -3 & -3 \\ 0 & 0 & 5 & 15 \end{array}\right]
5z=15→z=33y−3z=−3→y=−3+93=2x−y+z=2→x=2+2−3=1Check row 3: 1+4+9=14✓\begin{aligned} 5z &= 15 && \to z = 3 \\ 3y - 3z &= -3 && \to y = \frac{-3 + 9}{3} = 2 \\ x - y + z &= 2 && \to x = 2 + 2 - 3 = 1 \\ &\text{Check row 3: } 1 + 4 + 9 = 14 \checkmark \end{aligned}
python · try it yourself
from sympy import Matrix
print(list(Matrix([[1, -1, 1], [2, 1, -1], [1, 2, 3]]).solve(Matrix([2, 1, 14]))))
[1, 2, 3]

Exercise 3: Inconsistent or infinite?

Run elimination on x+2y=3x + 2y = 3, 2x+4y=k2x + 4y = k. For which kk is the system consistent, and how many solutions does it then have?

Answer

Consistent only for k=6k = 6, with infinitely many solutions (yy free, x=3−2yx = 3 - 2y).

Solution
R2←R2−2R1:[12300k−6]k≠6→0=k−6≠0→inconsistentk=6→one pivot, two variables→y=t free, x=3−2t\begin{aligned} &R_2 \leftarrow R_2 - 2R_1\text{:} \quad \left[\begin{array}{rr|c} 1 & 2 & 3 \\ 0 & 0 & k - 6 \end{array}\right] \\ &k \ne 6 \to 0 = k - 6 \ne 0 \to \text{inconsistent} \\ &k = 6 \to \text{one pivot, two variables} \to y = t \text{ free},\ x = 3 - 2t \end{aligned}

Exercise 4: A free variable (code)

Run the lesson's echelon function on x+y+z=6x + y + z = 6, 2x+2y+3z=142x + 2y + 3z = 14 (two equations, three unknowns). Which column has no pivot?

Answer

Pivots in columns 0 and 2; column 1 (yy) is free.

Solution

R2−2R1=(0,0,1∣2)R_2 - 2R_1 = (0, 0, 1 \mid 2), so the second pivot jumps to the zz column. Then z=2z = 2 and x=4−yx = 4 - y with yy free.

python · try it yourself
from fractions import Fraction as F

def echelon(M):
    M = [[F(a) for a in row] for row in M]
    rows, cols = len(M), len(M[0]) - 1
    pivots, r = [], 0
    for c in range(cols):
        p = next((i for i in range(r, rows) if M[i][c] != 0), None)
        if p is None:
            continue
        M[r], M[p] = M[p], M[r]
        for i in range(r + 1, rows):
            f = M[i][c] / M[r][c]
            M[i] = [a - f * b for a, b in zip(M[i], M[r])]
        pivots.append(c); r += 1
        if r == rows:
            break
    return M, pivots

E, piv = echelon([[1, 1, 1, 6], [2, 2, 3, 14]])
print([[str(a) for a in row] for row in E], piv)
[['1', '1', '1', '6'], ['0', '0', '1', '2']] [0, 2]

Test yourself

After elimination, a row reads [0 0 0∣7][0\ 0\ 0 \mid 7]. What does that mean?

  1. x3=7x_3 = 7
  2. The system is inconsistent
  3. There are infinitely many solutions
  4. The row can be deleted

A consistent system with 4 unknowns has 3 pivots after elimination. How many solutions?

  1. None
  2. Exactly one
  3. Exactly three
  4. Infinitely many

Why do floating-point implementations choose the largest available entry as the pivot?

  1. It is required for correctness with exact numbers
  2. It reduces the growth of rounding errors
  3. It makes the matrix symmetric
  4. It avoids back substitution