{"record":{"id":"f12b9d8be5971bf6","repo":"TheAlgorithms/Python","slug":"matrix-is-not-square","errorCode":null,"errorMessage":"Matrix is not square","messagePattern":"Matrix is not square","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"linear_algebra/src/gaussian_elimination_pivoting.py","lineNumber":41,"sourceCode":"    >>> solution = solve_linear_system(np.column_stack((A, B)))\n    >>> np.allclose(solution, np.array([2., 3., -1.]))\n    True\n    >>> solve_linear_system(np.array([[0, 0, 0]], dtype=float))\n    Traceback (most recent call last):\n        ...\n    ValueError: Matrix is not square\n    >>> solve_linear_system(np.array([[0, 0, 0], [0, 0, 0]], dtype=float))\n    Traceback (most recent call last):\n        ...\n    ValueError: Matrix is singular\n    \"\"\"\n    ab = np.copy(matrix)\n    num_of_rows = ab.shape[0]\n    num_of_columns = ab.shape[1] - 1\n    x_lst: list[float] = []\n\n    if num_of_rows != num_of_columns:\n        raise ValueError(\"Matrix is not square\")\n\n    for column_num in range(num_of_rows):\n        # Lead element search\n        for i in range(column_num, num_of_columns):\n            if abs(ab[i][column_num]) > abs(ab[column_num][column_num]):\n                ab[[column_num, i]] = ab[[i, column_num]]\n\n        # Upper triangular matrix\n        if abs(ab[column_num, column_num]) < 1e-8:\n            raise ValueError(\"Matrix is singular\")\n\n        if column_num != 0:\n            for i in range(column_num, num_of_rows):\n                ab[i, :] -= (\n                    ab[i, column_num - 1]\n                    / ab[column_num - 1, column_num - 1]\n                    * ab[column_num - 1, :]\n                )","sourceCodeStart":23,"sourceCodeEnd":59,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/src/gaussian_elimination_pivoting.py#L23-L59","documentation":"Raised by solve_linear_system() in linear_algebra/src/gaussian_elimination_pivoting.py:41 when the augmented matrix's dimensions are inconsistent: it takes num_of_rows = ab.shape[0] and num_of_columns = ab.shape[1] - 1 (last column holds the right-hand side), and requires num_of_rows == num_of_columns. So it fires when the number of equations does not equal the number of unknowns — the coefficient part is not square.","triggerScenarios":"Calling solve_linear_system() on an augmented array where rows != columns - 1, e.g. np.array([[1, 2, 3, 10], [4, 5, 6, 20]]) (2 equations, 3 unknowns), or passing a non-augmented square coefficient matrix (n x n is interpreted as n equations with n-1 unknowns).","commonSituations":"Forgetting to append the b column before calling (passing A alone), mixing up row-major construction of the augmented matrix, or feeding over-/under-determined systems from real data where the equation count does not match the variable count.","solutions":["Build the augmented matrix as np.column_stack((A, b)) where A is square (n x n) and b has length n, before calling.","If you passed the coefficient matrix alone, append the RHS column.","If the system is genuinely over- or under-determined, use np.linalg.lstsq instead of this square-system-only solver.","Verify matrix.shape == (n, n + 1) as an assertion at the call site."],"exampleFix":"// before\nA = np.array([[2, -1], [1, 3]])\nx = solve_linear_system(A.astype(float))  # ValueError: not square\n\n// after\nb = np.array([1, 2])\nab = np.column_stack((A, b)).astype(float)\nx = solve_linear_system(ab)","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef is_valid_augmented(ab: np.ndarray) -> bool:\n    return ab.ndim == 2 and ab.shape[1] == ab.shape[0] + 1  # n equations, n unknowns + RHS\n\nA = np.array([[2.0, -1.0], [1.0, 3.0]])\nb = np.array([1.0, 2.0])\nab = np.column_stack((A, b))\nassert is_valid_augmented(ab)","typeGuard":"def is_augmented_square_system(a) -> bool:\n    return hasattr(a, \"shape\") and len(a.shape) == 2 and a.shape[1] == a.shape[0] + 1","tryCatchPattern":"try:\n    x = solve_linear_system(ab)\nexcept ValueError as e:\n    if \"not square\" in str(e):\n        raise ValueError(f\"expected (n, n+1) augmented matrix, got {ab.shape}\") from e\n    raise","preventionTips":["Always build the augmented matrix with np.column_stack((A, b)) rather than hand-appending columns.","Keep the invariant A is (n, n) and b has length n in the system-construction layer.","For over-/under-determined systems (rows != unknowns), use np.linalg.lstsq — this solver is square-systems-only by design.","Check ab.shape == (n, n + 1) in one shared precondition helper instead of at each call site."],"tags":["linear-algebra","gaussian-elimination","linear-system","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}