{"record":{"id":"7093ed12395b031e","repo":"TheAlgorithms/Python","slug":"coefficient-matrix-dimensions-must-be-nxn-but-rece","errorCode":null,"errorMessage":"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}","messagePattern":"Coefficient matrix dimensions must be nxn but received (.+?)x(.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"linear_algebra/jacobi_iteration_method.py","lineNumber":88,"sourceCode":"    ValueError: Number of initial values must be equal to number of rows in coefficient\n                matrix but received 2 and 3\n\n    >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n    >>> 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)","sourceCodeStart":70,"sourceCodeEnd":106,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/jacobi_iteration_method.py#L70-L106","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Check coefficient_matrix.shape[0] == coefficient_matrix.shape[1] before calling and fix the system construction.","Wrap inputs in np.asarray(...) so .shape exists.","If the system is genuinely rectangular, use least squares (np.linalg.lstsq) instead of Jacobi."],"exampleFix":"# before\njacobi_iteration_method([[1, 2, 3], [4, 5, 6]], [[1], [2]], [0, 0], 100)\n\n# after\nA = np.asarray([[3, 1], [1, 4]], dtype=float)\nb = np.asarray([[1], [2]], dtype=float)\njacobi_iteration_method(A, b, np.zeros(2), 100)","handlingStrategy":"validation","validationCode":"A = np.asarray(coefficient_matrix, dtype=float)\nassert A.ndim == 2 and A.shape[0] == A.shape[1], f\"A must be square, got {A.shape}\"","typeGuard":"def is_square_matrix(m: object) -> bool:\n        return (\n        isinstance(m, np.ndarray)\n        and m.ndim == 2\n        and m.shape[0] == m.shape[1]\n    )","tryCatchPattern":"try:\n    x = jacobi_iteration_method(A, b, x0, iters)\nexcept ValueError as e:\n    if \"nxn\" in str(e):\n        raise ValueError(f\"system builder produced non-square A: {A.shape}\") from e\n    raise","preventionTips":["Always np.asarray inputs so .shape exists.","Assemble A row-by-row next to its b entry.","Use lstsq for genuinely rectangular systems."],"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"}