TheAlgorithms/Python · error · ValueError

Coefficient matrix dimensions must be nxn but received {rows

Error message

Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}

What it means

Thrown by jacobi_iteration_method() when the coefficient matrix is not square (rows1 != cols1). Jacobi iteration solves A·x = b by iteratively updating each x_i from row i, which requires one equation per unknown; a non-square A has no such decomposition and the method is undefined.

Source

Thrown at linear_algebra/jacobi_iteration_method.py:88

    ValueError: Number of initial values must be equal to number of rows in coefficient
                matrix but received 2 and 3

    >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
    >>> constant = np.array([[2], [-6], [-4]])
    >>> init_val = [0.5, -0.5, -0.5]
    >>> iterations = 0
    >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
    Traceback (most recent call last):
        ...
    ValueError: Iterations must be at least 1
    """

    rows1, cols1 = coefficient_matrix.shape
    rows2, cols2 = constant_matrix.shape

    if rows1 != cols1:
        msg = f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
        raise ValueError(msg)

    if cols2 != 1:
        msg = f"Constant matrix must be nx1 but received {rows2}x{cols2}"
        raise ValueError(msg)

    if rows1 != rows2:
        msg = (
            "Coefficient and constant matrices dimensions must be nxn and nx1 but "
            f"received {rows1}x{cols1} and {rows2}x{cols2}"
        )
        raise ValueError(msg)

    if len(init_val) != rows1:
        msg = (
            "Number of initial values must be equal to number of rows in coefficient "
            f"matrix but received {len(init_val)} and {rows1}"
        )
        raise ValueError(msg)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check coefficient_matrix.shape[0] == coefficient_matrix.shape[1] before calling and fix the system construction.
  2. Wrap inputs in np.asarray(...) so .shape exists.
  3. If the system is genuinely rectangular, use least squares (np.linalg.lstsq) instead of Jacobi.

Example fix

# before
jacobi_iteration_method([[1, 2, 3], [4, 5, 6]], [[1], [2]], [0, 0], 100)

# after
A = np.asarray([[3, 1], [1, 4]], dtype=float)
b = np.asarray([[1], [2]], dtype=float)
jacobi_iteration_method(A, b, np.zeros(2), 100)
Defensive patterns

Strategy: validation

Validate before calling

A = np.asarray(coefficient_matrix, dtype=float)
assert A.ndim == 2 and A.shape[0] == A.shape[1], f"A must be square, got {A.shape}"

Type guard

def is_square_matrix(m: object) -> bool:
        return (
        isinstance(m, np.ndarray)
        and m.ndim == 2
        and m.shape[0] == m.shape[1]
    )

Try / catch

try:
    x = jacobi_iteration_method(A, b, x0, iters)
except ValueError as e:
    if "nxn" in str(e):
        raise ValueError(f"system builder produced non-square A: {A.shape}") from e
    raise

Prevention

When it happens

Trigger: Calling jacobi_iteration_method(np.array([[1,2,3],[4,5,6]]), b, init_val, iterations) — a 2x3 coefficient matrix. Also passing a nested Python list, which has no .shape attribute and raises AttributeError instead — convert with np.asarray first.

Common situations: Under/over-determined systems assembled from data (more equations than unknowns or vice versa); a dropped column during data cleanup; passing raw lists instead of numpy arrays.

Related errors


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