{"record":{"id":"e8dce5cee1858496","repo":"TheAlgorithms/Python","slug":"table-has-to-be-of-square-shaped-array-but-got-a","errorCode":null,"errorMessage":"'table' has to be of square shaped array but got a {rows}x{columns} array:\\n{table}","messagePattern":"'table' has to be of square shaped array but got a (.+?)x(.+?) array:\\\\n(.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"linear_algebra/lu_decomposition.py","lineNumber":90,"sourceCode":"    >>> upper_mat\n    array([[1., 0.],\n           [0., 0.]])\n\n    >>> # Matrix is singular, but its first leading principal minor is 0\n    >>> matrix = np.array([[0, 1], [0, 1]])\n    >>> lower_mat, upper_mat = lower_upper_decomposition(matrix)\n    Traceback (most recent call last):\n    ...\n    ArithmeticError: No LU decomposition exists\n    \"\"\"\n    # Ensure that table is a square array\n    rows, columns = np.shape(table)\n    if rows != columns:\n        msg = (\n            \"'table' has to be of square shaped array but got a \"\n            f\"{rows}x{columns} array:\\n{table}\"\n        )\n        raise ValueError(msg)\n\n    lower = np.zeros((rows, columns))\n    upper = np.zeros((rows, columns))\n\n    # in 'total', the necessary data is extracted through slices\n    # and the sum of the products is obtained.\n\n    for i in range(columns):\n        for j in range(i):\n            total = np.sum(lower[i, :i] * upper[:i, j])\n            if upper[j][j] == 0:\n                raise ArithmeticError(\"No LU decomposition exists\")\n            lower[i][j] = (table[i][j] - total) / upper[j][j]\n        lower[i][i] = 1\n        for j in range(i, columns):\n            total = np.sum(lower[i, :i] * upper[:i, j])\n            upper[i][j] = table[i][j] - total\n    return lower, upper","sourceCodeStart":72,"sourceCodeEnd":108,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/lu_decomposition.py#L72-L108","documentation":"Raised by lower_upper_decomposition() in linear_algebra/lu_decomposition.py:90 when the input `table` is not a square (n x n) matrix. LU decomposition as implemented (Doolittle, no pivoting) only factors square matrices, so the function first checks np.shape(table) and rejects any array where rows != columns. The error message embeds the actual rows x columns dimensions and the full matrix contents.","triggerScenarios":"Calling lower_upper_decomposition(table) with any non-square ndarray, e.g. np.array([[2, -2, 1], [0, 1, 2]]) (2x3). Also triggered when a matrix built from ragged data or a transposed/reshaped array accidentally has mismatched dimensions.","commonSituations":"Loading data from CSV where one row has a missing/extra column, slicing a matrix incorrectly (e.g. matrix[:, :2] on a 3x3), passing an augmented [A|b] system matrix intended for a solver, or building the matrix from a list of rows of unequal length that NumPy tolerates as a wider array.","solutions":["Check table.shape[0] == table.shape[1] before calling and fix the construction of the matrix so it is square.","Print table.shape right before the call to find where the dimensions diverge from expectations.","If you meant to solve a linear system (not factor it), pass only the coefficient matrix A, not the augmented [A|b].","Wrap the call in try/except ValueError to reject bad input gracefully at a system boundary."],"exampleFix":"// before\nmatrix = np.array([[2, -2, 1], [0, 1, 2]])\nlower, upper = lower_upper_decomposition(matrix)  # ValueError: 2x3\n\n// after\nmatrix = np.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]])\nassert matrix.shape[0] == matrix.shape[1], f\"expected square, got {matrix.shape}\"\nlower, upper = lower_upper_decomposition(matrix)","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef is_square(table: np.ndarray) -> bool:\n    return table.ndim == 2 and table.shape[0] == table.shape[1]\n\nif not is_square(matrix):\n    raise ValueError(f\"LU decomposition needs a square matrix, got {matrix.shape}\")\nlower, upper = lower_upper_decomposition(matrix)","typeGuard":"def is_square_matrix(a) -> bool:\n    return hasattr(a, \"shape\") and len(a.shape) == 2 and a.shape[0] == a.shape[1]","tryCatchPattern":"try:\n    lower, upper = lower_upper_decomposition(matrix)\nexcept ValueError as e:\n    raise ValueError(f\"rejected non-square input {getattr(matrix, 'shape', '?')}: {e}\") from e","preventionTips":["Assert table.shape[0] == table.shape[1] at every site where a matrix is assembled from external data.","Use np.asarray(data) and check .shape before calling; ragged lists either fail earlier or reveal wrong dimensions here.","Never pass an augmented [A|b] matrix to a factorization function; pass only the coefficient block.","Keep matrix construction in one place (loader/builder function) so dimension bugs surface once, not at call sites."],"tags":["linear-algebra","matrix","validation","lu-decomposition","numpy"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}