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

Cannot add shapes and

Error message

Cannot add shapes {self.shape} and {other.shape}

What it means

Raised in Matrix.__add__ when the right-hand matrix matches neither the same shape nor the broadcastable row-vector (1 x cols) or column-vector (rows x 1) forms. Element-wise addition is undefined for these incompatible shapes, and Python has no silent broadcasting fallback in this hand-rolled implementation.

Solutions

  1. Reshape or transpose one operand so both matrices share the same shape
  2. Wrap the addition in a shape check and fall back to explicit broadcasting when a 1xN or Nx1 matrix is intended
  3. Fix upstream math that produced an unexpectedly shaped matrix (e.g. a missing transpose)
Defensive patterns

Strategy: validation

When it happens

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

Appendix: source

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

    def __add__(self, other):
        if isinstance(other, Matrix):
            if other.shape == self.shape:
                return Matrix([
                    [self.data[i][j] + other.data[i][j] for j in range(self.cols)]
                    for i in range(self.rows)
                ])
            if other.rows == 1 and other.cols == self.cols:
                return Matrix([
                    [self.data[i][j] + other.data[0][j] for j in range(self.cols)]
                    for i in range(self.rows)
                ])
            if other.cols == 1 and other.rows == self.rows:
                return Matrix([
                    [self.data[i][j] + other.data[i][0] for j in range(self.cols)]
                    for i in range(self.rows)
                ])
        raise ValueError(f"Cannot add shapes {self.shape} and {other.shape}")

    def __sub__(self, other):
        return Matrix([
            [self.data[i][j] - other.data[i][j] for j in range(self.cols)]
            for i in range(self.rows)
        ])

    def scalar_multiply(self, scalar):
        return Matrix([
            [self.data[i][j] * scalar for j in range(self.cols)]
            for i in range(self.rows)
        ])

    def element_wise_multiply(self, other):
        return Matrix([
            [self.data[i][j] * other.data[i][j] for j in range(self.cols)]
            for i in range(self.rows)
        ])

View on GitHub (pinned to 39ea8a1c6d)