{"record":{"id":"86556c04ca2cc016","repo":"TheAlgorithms/Python","slug":"only-square-matrices-can-be-raised-to-a-power","errorCode":null,"errorMessage":"Only square matrices can be raised to a power","messagePattern":"Only square matrices can be raised to a power","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_class.py","lineNumber":344,"sourceCode":"                    \"The number of columns in the first matrix must \"\n                    \"be equal to the number of rows in the second\"\n                )\n            return Matrix(\n                [\n                    [Matrix.dot_product(row, column) for column in other.columns()]\n                    for row in self.rows\n                ]\n            )\n        else:\n            raise TypeError(\n                \"A Matrix can only be multiplied by an int, float, or another matrix\"\n            )\n\n    def __pow__(self, other: int) -> Matrix:\n        if not isinstance(other, int):\n            raise TypeError(\"A Matrix can only be raised to the power of an int\")\n        if not self.is_square:\n            raise ValueError(\"Only square matrices can be raised to a power\")\n        if other == 0:\n            return self.identity()\n        if other < 0:\n            if self.is_invertable():\n                return self.inverse() ** (-other)\n            raise ValueError(\n                \"Only invertable matrices can be raised to a negative power\"\n            )\n        result = self\n        for _ in range(other - 1):\n            result *= self\n        return result\n\n    @classmethod\n    def dot_product(cls, row: list[int], column: list[int]) -> int:\n        return sum(row[i] * column[i] for i in range(len(row)))\n\n","sourceCodeStart":326,"sourceCodeEnd":362,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_class.py#L326-L362","documentation":"Raised by Matrix.__pow__ when the base matrix is not square. Matrix powers (positive via repeated multiplication, zero via identity, negative via inverse) are only defined for n x n matrices, so the method checks self.is_square before anything else. A non-square matrix has no power for any exponent, including 0 in this implementation's contract.","triggerScenarios":"Calling matrix ** k on any m x n matrix where m != n, e.g. a 2x3 Matrix raised to power 2, or a row-vector Matrix raised to power 0. The check fires before the exponent sign is even examined.","commonSituations":"Applying transformation matrices to data matrices (e.g. raising a data matrix instead of the covariance/transition matrix to a power); assuming A**0 returns something for rectangular matrices; graph adjacency matrices built with a bug that drops a row.","solutions":["Inspect the matrix dimensions (num_rows vs num_columns) and fix the upstream construction so the matrix is square.","If you meant to multiply by itself a rectangular layout, reconsider the operation: compute A * A.transpose() or use a different algebraic formulation.","If a square transition/weight matrix was intended, check for a dropped row/column when parsing input data (e.g. a header line skipped incorrectly).","Unit-test matrix construction with an is_square assertion before powering."],"exampleFix":"# before\nm = Matrix([[1, 2, 3], [4, 5, 6]])\nresult = m ** 2  # ValueError: not square\n\n# after\nsquare = m * m.transpose()  # 2x3 * 3x2 -> 2x2, now powerable\nresult = square ** 2","handlingStrategy":"validation","validationCode":"if not matrix.is_square:\n    raise ValueError(\n        f\"matrix is {matrix.num_rows}x{matrix.num_columns}; powers need a square matrix\"\n    )\nresult = matrix ** k","typeGuard":"def is_square_matrix(m: Matrix) -> bool:\n    \"\"\"Guard: object is a Matrix with equal row/column counts.\"\"\"\n    return isinstance(m, Matrix) and m.num_rows == m.num_columns","tryCatchPattern":"try:\n    result = matrix ** k\nexcept ValueError as e:\n    if \"square\" in str(e):\n        # restate the actual shape for easier debugging\n        raise ValueError(f\"non-square {matrix.num_rows}x{matrix.num_columns} matrix\") from e\n    raise","preventionTips":["Assert is_square right after constructing any matrix destined for powers.","When parsing data into matrices, verify row count equals column count (no dropped header/footer lines).","For rectangular data, compute A @ A.T (a square product) before powering."],"tags":["matrix","valueerror","square-matrix","linear-algebra"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}