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

Determinant only defined for square matrices

Error message

Determinant only defined for square matrices

What it means

Error "Determinant only defined for square matrices" thrown in rohitg00/ai-engineering-from-scratch.

Source

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

            for i in range(self.rows)
        ])

    def __matmul__(self, other):
        return self.matmul(other)

    def transpose(self):
        return Matrix([
            [self.data[j][i] for j in range(self.rows)]
            for i in range(self.cols)
        ])

    @property
    def T(self):
        return self.transpose()

    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:

View on GitHub (pinned to 39ea8a1c6d)

When it happens

Trigger: Thrown at phases/01-math-foundations/02-vectors-matrices-operations/code/matrices.py:121 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/da095440501a347c. Report an issue: GitHub.