TheAlgorithms/Python · error · ValueError

Matrix is not square

Error message

Matrix is not square

What it means

Raised by solve_linear_system() in linear_algebra/src/gaussian_elimination_pivoting.py:41 when the augmented matrix's dimensions are inconsistent: it takes num_of_rows = ab.shape[0] and num_of_columns = ab.shape[1] - 1 (last column holds the right-hand side), and requires num_of_rows == num_of_columns. So it fires when the number of equations does not equal the number of unknowns — the coefficient part is not square.

Source

Thrown at linear_algebra/src/gaussian_elimination_pivoting.py:41

    >>> solution = solve_linear_system(np.column_stack((A, B)))
    >>> np.allclose(solution, np.array([2., 3., -1.]))
    True
    >>> solve_linear_system(np.array([[0, 0, 0]], dtype=float))
    Traceback (most recent call last):
        ...
    ValueError: Matrix is not square
    >>> solve_linear_system(np.array([[0, 0, 0], [0, 0, 0]], dtype=float))
    Traceback (most recent call last):
        ...
    ValueError: Matrix is singular
    """
    ab = np.copy(matrix)
    num_of_rows = ab.shape[0]
    num_of_columns = ab.shape[1] - 1
    x_lst: list[float] = []

    if num_of_rows != num_of_columns:
        raise ValueError("Matrix is not square")

    for column_num in range(num_of_rows):
        # Lead element search
        for i in range(column_num, num_of_columns):
            if abs(ab[i][column_num]) > abs(ab[column_num][column_num]):
                ab[[column_num, i]] = ab[[i, column_num]]

        # Upper triangular matrix
        if abs(ab[column_num, column_num]) < 1e-8:
            raise ValueError("Matrix is singular")

        if column_num != 0:
            for i in range(column_num, num_of_rows):
                ab[i, :] -= (
                    ab[i, column_num - 1]
                    / ab[column_num - 1, column_num - 1]
                    * ab[column_num - 1, :]
                )

View on GitHub (pinned to f5988cc097)

Solutions

  1. Build the augmented matrix as np.column_stack((A, b)) where A is square (n x n) and b has length n, before calling.
  2. If you passed the coefficient matrix alone, append the RHS column.
  3. If the system is genuinely over- or under-determined, use np.linalg.lstsq instead of this square-system-only solver.
  4. Verify matrix.shape == (n, n + 1) as an assertion at the call site.

Example fix

// before
A = np.array([[2, -1], [1, 3]])
x = solve_linear_system(A.astype(float))  # ValueError: not square

// after
b = np.array([1, 2])
ab = np.column_stack((A, b)).astype(float)
x = solve_linear_system(ab)
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def is_valid_augmented(ab: np.ndarray) -> bool:
    return ab.ndim == 2 and ab.shape[1] == ab.shape[0] + 1  # n equations, n unknowns + RHS

A = np.array([[2.0, -1.0], [1.0, 3.0]])
b = np.array([1.0, 2.0])
ab = np.column_stack((A, b))
assert is_valid_augmented(ab)

Type guard

def is_augmented_square_system(a) -> bool:
    return hasattr(a, "shape") and len(a.shape) == 2 and a.shape[1] == a.shape[0] + 1

Try / catch

try:
    x = solve_linear_system(ab)
except ValueError as e:
    if "not square" in str(e):
        raise ValueError(f"expected (n, n+1) augmented matrix, got {ab.shape}") from e
    raise

Prevention

When it happens

Trigger: Calling solve_linear_system() on an augmented array where rows != columns - 1, e.g. np.array([[1, 2, 3, 10], [4, 5, 6, 20]]) (2 equations, 3 unknowns), or passing a non-augmented square coefficient matrix (n x n is interpreted as n equations with n-1 unknowns).

Common situations: Forgetting to append the b column before calling (passing A alone), mixing up row-major construction of the augmented matrix, or feeding over-/under-determined systems from real data where the equation count does not match the variable count.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/f12b9d8be5971bf6. Report an issue: GitHub.