TheAlgorithms/Python · error · ValueError

Constant matrix must be nx1 but received {rows2}x{cols2}

Error message

Constant matrix must be nx1 but received {rows2}x{cols2}

What it means

Thrown by jacobi_iteration_method() when the constant (right-hand-side) matrix is not a single column (cols2 != 1). The Jacobi update x_i = (b_i - sum(a_ij * x_j)) / a_ii consumes exactly one b value per row; a wide constant matrix has no defined b_i and is rejected.

Source

Thrown at linear_algebra/jacobi_iteration_method.py:92

    >>> 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)

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

View on GitHub (pinned to f5988cc097)

Solutions

  1. Reshape the RHS to a column: constant_matrix = np.asarray(b, dtype=float).reshape(-1, 1).
  2. Verify constant_matrix.shape == (n, 1) matches the n x n coefficient matrix before the call.
  3. For multiple right-hand sides, loop over columns, one Jacobi call each.

Example fix

# before
jacobi_iteration_method(A, np.array([1.0, 2.0]), x0, 100)  # shape (2,) -> cols2 != 1

# after
b = np.array([1.0, 2.0]).reshape(-1, 1)
jacobi_iteration_method(A, b, x0, 100)
Defensive patterns

Strategy: validation

Validate before calling

b = np.asarray(constant, dtype=float)
if b.ndim == 1:
    b = b.reshape(-1, 1)
assert b.shape[1] == 1, f"b must be nx1, got {b.shape}"

Type guard

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

Try / catch

try:
    x = jacobi_iteration_method(A, b, x0, iters)
except ValueError as e:
    if "nx1" in str(e) and b.ndim == 1:
        x = jacobi_iteration_method(A, b.reshape(-1, 1), x0, iters)
    else:
        raise

Prevention

When it happens

Trigger: Calling jacobi_iteration_method(A, np.array([[1, 2], [3, 4]]), init_val, iterations) — a 2x2 constant matrix. Also passing a 1-D b like np.array([1, 2]) whose shape is (2,) — reshape to (2, 1) first.

Common situations: Using a naturally 1-D right-hand side vector and forgetting to reshape; transposing errors when assembling the system; passing multiple RHS columns intended for np.linalg.solve-style batch solving.

Related errors


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