TheAlgorithms/Python · error · ValueError
'table' has to be of square shaped array but got a {rows}x{c
Error message
'table' has to be of square shaped array but got a {rows}x{columns} array:\n{table} What it means
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.
Source
Thrown at linear_algebra/lu_decomposition.py:90
>>> upper_mat
array([[1., 0.],
[0., 0.]])
>>> # Matrix is singular, but its first leading principal minor is 0
>>> matrix = np.array([[0, 1], [0, 1]])
>>> lower_mat, upper_mat = lower_upper_decomposition(matrix)
Traceback (most recent call last):
...
ArithmeticError: No LU decomposition exists
"""
# Ensure that table is a square array
rows, columns = np.shape(table)
if rows != columns:
msg = (
"'table' has to be of square shaped array but got a "
f"{rows}x{columns} array:\n{table}"
)
raise ValueError(msg)
lower = np.zeros((rows, columns))
upper = np.zeros((rows, columns))
# in 'total', the necessary data is extracted through slices
# and the sum of the products is obtained.
for i in range(columns):
for j in range(i):
total = np.sum(lower[i, :i] * upper[:i, j])
if upper[j][j] == 0:
raise ArithmeticError("No LU decomposition exists")
lower[i][j] = (table[i][j] - total) / upper[j][j]
lower[i][i] = 1
for j in range(i, columns):
total = np.sum(lower[i, :i] * upper[:i, j])
upper[i][j] = table[i][j] - total
return lower, upperView on GitHub (pinned to f5988cc097)
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.
Example fix
// before
matrix = np.array([[2, -2, 1], [0, 1, 2]])
lower, upper = lower_upper_decomposition(matrix) # ValueError: 2x3
// after
matrix = np.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]])
assert matrix.shape[0] == matrix.shape[1], f"expected square, got {matrix.shape}"
lower, upper = lower_upper_decomposition(matrix) Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
def is_square(table: np.ndarray) -> bool:
return table.ndim == 2 and table.shape[0] == table.shape[1]
if not is_square(matrix):
raise ValueError(f"LU decomposition needs a square matrix, got {matrix.shape}")
lower, upper = lower_upper_decomposition(matrix) Type guard
def is_square_matrix(a) -> bool:
return hasattr(a, "shape") and len(a.shape) == 2 and a.shape[0] == a.shape[1] Try / catch
try:
lower, upper = lower_upper_decomposition(matrix)
except ValueError as e:
raise ValueError(f"rejected non-square input {getattr(matrix, 'shape', '?')}: {e}") from e Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- determinant modular {req_l} of encryption key({det}) is not
- Coefficient matrix dimensions must be nxn but received {rows
- Constant matrix must be nx1 but received {rows2}x{cols2}
- Coefficient and constant matrices dimensions must be nxn and
- Number of initial values must be equal to number of rows in
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/e8dce5cee1858496.
Report an issue: GitHub.