TheAlgorithms/Python · error · ValueError

Coefficient and constant matrices dimensions must be nxn and

Error message

Coefficient and constant matrices dimensions must be nxn and nx1 but received {rows1}x{cols1} and {rows2}x{cols2}

What it means

Thrown by jacobi_iteration_method() when the coefficient matrix's row count differs from the constant matrix's row count (rows1 != rows2). Each unknown needs exactly one equation with its own b entry; mismatched row counts mean the system A·x = b is not even well-formed for the iteration.

Source

Thrown at linear_algebra/jacobi_iteration_method.py:99

    """

    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)

    if iterations <= 0:
        raise ValueError("Iterations must be at least 1")

    table: NDArray[float64] = np.concatenate(
        (coefficient_matrix, constant_matrix), axis=1
    )

    rows, _cols = table.shape

    strictly_diagonally_dominant(table)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Derive both from one item list so lengths stay in lockstep.
  2. Assert A.shape[0] == b.shape[0] at system-assembly time.
  3. Log both shapes on failure to spot which side lost the row.

Example fix

# before
A = np.array([[4, 1], [1, 3], [2, 2]])   # 3 rows
b = np.array([[1], [2]])                  # 2 rows

# after
rows = [(np.array([4, 1]), 1), (np.array([1, 3]), 2)]
A = np.array([r for r, _ in rows], dtype=float)
b = np.array([[v] for _, v in rows], dtype=float)
Defensive patterns

Strategy: validation

Validate before calling

assert A.shape[0] == b.shape[0], (
    f"A has {A.shape[0]} rows but b has {b.shape[0]}"
)

Type guard

def is_matching_system(A: np.ndarray, b: np.ndarray) -> bool:
        return (
        A.ndim == 2
        and b.ndim == 2
        and A.shape[0] == b.shape[0]
        and A.shape[1] == A.shape[0]
        and b.shape[1] == 1
    )

Try / catch

try:
    x = jacobi_iteration_method(A, b, x0, iters)
except ValueError as e:
    if "dimensions" in str(e):
        raise ValueError(f"A/b assembled out of sync: {A.shape} vs {b.shape}") from e
    raise

Prevention

When it happens

Trigger: Calling with a 3x3 coefficient matrix and a 2x1 constant matrix (e.g. one equation lost when assembling from data). Typically follows fixing earlier shape errors — A is made square but b is not resized to match.

Common situations: Assembling A and b in separate code paths so one drops a row; appending an equation to A without extending b; refactors that change n in one place only.

Related errors


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