{"record":{"id":"598e323e6acde500","repo":"TheAlgorithms/Python","slug":"constant-matrix-must-be-nx1-but-received-rows2-x","errorCode":null,"errorMessage":"Constant matrix must be nx1 but received {rows2}x{cols2}","messagePattern":"Constant matrix must be nx1 but received (.+?)x(.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"linear_algebra/jacobi_iteration_method.py","lineNumber":92,"sourceCode":"    >>> constant = np.array([[2], [-6], [-4]])\n    >>> init_val = [0.5, -0.5, -0.5]\n    >>> iterations = 0\n    >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n    Traceback (most recent call last):\n        ...\n    ValueError: Iterations must be at least 1\n    \"\"\"\n\n    rows1, cols1 = coefficient_matrix.shape\n    rows2, cols2 = constant_matrix.shape\n\n    if rows1 != cols1:\n        msg = f\"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}\"\n        raise ValueError(msg)\n\n    if cols2 != 1:\n        msg = f\"Constant matrix must be nx1 but received {rows2}x{cols2}\"\n        raise ValueError(msg)\n\n    if rows1 != rows2:\n        msg = (\n            \"Coefficient and constant matrices dimensions must be nxn and nx1 but \"\n            f\"received {rows1}x{cols1} and {rows2}x{cols2}\"\n        )\n        raise ValueError(msg)\n\n    if len(init_val) != rows1:\n        msg = (\n            \"Number of initial values must be equal to number of rows in coefficient \"\n            f\"matrix but received {len(init_val)} and {rows1}\"\n        )\n        raise ValueError(msg)\n\n    if iterations <= 0:\n        raise ValueError(\"Iterations must be at least 1\")\n","sourceCodeStart":74,"sourceCodeEnd":110,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/jacobi_iteration_method.py#L74-L110","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Reshape the RHS to a column: constant_matrix = np.asarray(b, dtype=float).reshape(-1, 1).","Verify constant_matrix.shape == (n, 1) matches the n x n coefficient matrix before the call.","For multiple right-hand sides, loop over columns, one Jacobi call each."],"exampleFix":"# before\njacobi_iteration_method(A, np.array([1.0, 2.0]), x0, 100)  # shape (2,) -> cols2 != 1\n\n# after\nb = np.array([1.0, 2.0]).reshape(-1, 1)\njacobi_iteration_method(A, b, x0, 100)","handlingStrategy":"validation","validationCode":"b = np.asarray(constant, dtype=float)\nif b.ndim == 1:\n    b = b.reshape(-1, 1)\nassert b.shape[1] == 1, f\"b must be nx1, got {b.shape}\"","typeGuard":"def is_column_vector(b: object) -> bool:\n        return isinstance(b, np.ndarray) and b.ndim == 2 and b.shape[1] == 1","tryCatchPattern":"try:\n    x = jacobi_iteration_method(A, b, x0, iters)\nexcept ValueError as e:\n    if \"nx1\" in str(e) and b.ndim == 1:\n        x = jacobi_iteration_method(A, b.reshape(-1, 1), x0, iters)\n    else:\n        raise","preventionTips":["Reshape 1-D right-hand sides to (-1, 1) before calling.","Solve multiple RHS columns in a loop, one per call.","Standardize on (n, 1) column vectors in your solver wrappers."],"tags":["linear-algebra","jacobi","numpy","validation","matrix-shape"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}