TheAlgorithms/Python · error · Exception
Matrix is not square
Error message
Matrix is not square
What it means
Raised by Matrix.minor(x, y) in linear_algebra/src/lib.py:388 when the matrix is not square (height != width). A minor is the determinant of the submatrix obtained by deleting row x and column y, and the code immediately builds that submatrix and calls .determinant() — which also requires squareness — so non-square input is rejected up front with a bare Exception.
Source
Thrown at linear_algebra/src/lib.py:388
return self.__matrix[x][y]
else:
raise Exception("change_component: indices out of bounds")
def change_component(self, x: int, y: int, value: float) -> None:
"""
changes the x-y component of this matrix
"""
if 0 <= x < self.__height and 0 <= y < self.__width:
self.__matrix[x][y] = value
else:
raise Exception("change_component: indices out of bounds")
def minor(self, x: int, y: int) -> float:
"""
returns the minor along (x, y)
"""
if self.__height != self.__width:
raise Exception("Matrix is not square")
minor = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(minor)):
minor[i] = minor[i][:y] + minor[i][y + 1 :]
return Matrix(minor, self.__width - 1, self.__height - 1).determinant()
def cofactor(self, x: int, y: int) -> float:
"""
returns the cofactor (signed minor) along (x, y)
"""
if self.__height != self.__width:
raise Exception("Matrix is not square")
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(x, y)
else:
raise Exception("Indices out of bounds")
def determinant(self) -> float:
"""View on GitHub (pinned to f5988cc097)
Solutions
- Check m.height() == m.width() before calling minor()/cofactor()/determinant().
- Verify the (width, height) constructor arguments actually describe the nested list — swapped arguments make square data look rectangular.
- For rectangular matrices, minors are undefined; compute rank/SVD or crop to a square submatrix explicitly if that is what you meant.
- Catch Exception narrowly at boundaries.
Example fix
// before
m = Matrix([[1, 2, 3], [4, 5, 6]], 3, 2)
m.minor(0, 0) # Exception: Matrix is not square
// after
assert m.height() == m.width(), f"minor needs a square matrix, got {m.height()}x{m.width()}"
m.minor(0, 0) Defensive patterns
Strategy: validation
Validate before calling
if m.height() != m.width():
raise ValueError(f"minor requires a square matrix, got {m.height()}x{m.width()}")
value = m.minor(x, y) Type guard
from linear_algebra.src.lib import Matrix
def is_square_matrix(m) -> bool:
return isinstance(m, Matrix) and m.height() == m.width() Try / catch
try:
value = m.minor(x, y)
except Exception as e:
if "not square" in str(e):
raise ValueError(f"cannot take minor of {m.height()}x{m.width()} matrix") from e
raise Prevention
- Guard every minor/cofactor/determinant entry point with a squareness check — all three require it.
- Confirm the Matrix(data, width, height) constructor arguments match the nested list; swapped args fake rectangularity.
- Keep determinant-family operations on a dedicated square-matrix type/path so rectangular data cannot reach them.
- Validate at load time that row count equals column count when squareness is an invariant of your data.
When it happens
Trigger: Calling minor() on any m x n Matrix with m != n, e.g. Matrix([[1, 2, 3], [4, 5, 6]], 3, 2).minor(0, 0). Typically hit while computing cofactors/determinants of rectangular data, or when the constructor's width/height arguments were swapped, making an intentionally square matrix rectangular.
Common situations: Feeding rectangular data tables into determinant-style computations, or dimension-argument mix-ups at Matrix construction (signature is (matrix, width, height)).
Related errors
- determinant modular {req_l} of encryption key({det}) is not
- 'table' has to be of square shaped array but got a {rows}x{c
- matrix must have the same dimension!
- matrices must have the same dimension!
- vector must have the same size as the number of columns of t
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/851cafce2e6ac78f.
Report an issue: GitHub.