rohitg00/ai-engineering-from-scratch · error · ValueError

This method only works for 2x2 matrices

Error message

This method only works for 2x2 matrices

What it means

Raised in Matrix.inverse_2x2 when the matrix's shape is not exactly (2, 2). This educational implementation hard-codes the closed-form 2x2 inverse (swap diagonal, negate off-diagonal, divide by determinant) and deliberately does not generalize.

Solutions

  1. Use a 2x2 matrix, or implement/switch to a general method (Gaussian elimination) for larger sizes
  2. Reduce/slice the problem to 2x2 blocks if the lesson only needs the closed form
  3. Check the shape before calling inverse_2x2 in callers that may receive larger matrices
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/01-math-foundations/02-vectors-matrices-operations/code/matrices.py:137 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/ea4a16dec9ae48d1. Report an issue: GitHub.

Appendix: source

Thrown at phases/01-math-foundations/02-vectors-matrices-operations/code/matrices.py:137

    def determinant(self):
        if self.rows != self.cols:
            raise ValueError("Determinant only defined for square matrices")
        if self.shape == (1, 1):
            return self.data[0][0]
        if self.shape == (2, 2):
            return self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0]
        det = 0
        for j in range(self.cols):
            minor = Matrix([
                [self.data[i][k] for k in range(self.cols) if k != j]
                for i in range(1, self.rows)
            ])
            det += ((-1) ** j) * self.data[0][j] * minor.determinant()
        return det

    def inverse_2x2(self):
        if self.shape != (2, 2):
            raise ValueError("This method only works for 2x2 matrices")
        det = self.determinant()
        if abs(det) < 1e-10:
            raise ValueError("Matrix is singular, no inverse exists")
        return Matrix([
            [self.data[1][1] / det, -self.data[0][1] / det],
            [-self.data[1][0] / det, self.data[0][0] / det]
        ])

    @staticmethod
    def identity(n):
        return Matrix([
            [1 if i == j else 0 for j in range(n)]
            for i in range(n)
        ])

    @staticmethod
    def zeros(rows, cols):
        return Matrix([[0] * cols for _ in range(rows)])

View on GitHub (pinned to 39ea8a1c6d)