{"record":{"id":"f0fa6bb0a91c9828","repo":"TheAlgorithms/Python","slug":"invalid-matrix-dimensions","errorCode":null,"errorMessage":"Invalid matrix dimensions","messagePattern":"Invalid matrix dimensions","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_multiplication_recursion.py","lineNumber":113,"sourceCode":"    >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_wide)\n    Traceback (most recent call last):\n        ...\n    ValueError: Invalid matrix dimensions\n    >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_high)\n    Traceback (most recent call last):\n        ...\n    ValueError: Invalid matrix dimensions\n    >>> matrix_multiply_recursive(matrix_1_to_4, matrix_count_up)\n    Traceback (most recent call last):\n        ...\n    ValueError: Invalid matrix dimensions\n    \"\"\"\n    if not matrix_a or not matrix_b:\n        return []\n    if not all(\n        (len(matrix_a) == len(matrix_b), is_square(matrix_a), is_square(matrix_b))\n    ):\n        raise ValueError(\"Invalid matrix dimensions\")\n\n    # Initialize the result matrix with zeros\n    result = [[0] * len(matrix_b[0]) for _ in range(len(matrix_a))]\n\n    # Recursive multiplication of matrices\n    def multiply(\n        i_loop: int,\n        j_loop: int,\n        k_loop: int,\n        matrix_a: Matrix,\n        matrix_b: Matrix,\n        result: Matrix,\n    ) -> None:\n        \"\"\"\n        :param matrix_a: A square Matrix.\n        :param matrix_b: Another square Matrix with the same dimensions as matrix_a.\n        :param result: Result matrix\n        :param i: Index used for iteration during multiplication.","sourceCodeStart":95,"sourceCodeEnd":131,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_multiplication_recursion.py#L95-L131","documentation":"Raised by matrix_multiply_recursive when either input matrix is not square, or the two matrices do not have the same dimension. This recursive block-multiplication implementation only supports equal-sized square matrices (it splits matrices into quadrants), which is far stricter than general matrix multiplication. Empty matrices short-circuit to [] instead.","triggerScenarios":"matrix_multiply_recursive([[1, 2], [3, 4]], [[1, 2, 3], [4, 5, 6]]) (second not square), or multiplying a 2x2 by a 3x3. Any non-square operand or size mismatch between two square operands triggers it.","commonSituations":"Assuming this helper is a general multiplier because of its name; feeding rectangular data matrices from a dataset; porting code from NumPy dot() which handles any compatible shapes.","solutions":["Pre-check with the module's is_square() helper on both matrices and len equality before calling.","If your matrices are rectangular but compatible (cols_a == rows_b), use the general algorithm in matrix_operation.multiply or matrix_class.Matrix.__mul__ instead.","Pad rectangular matrices to square with zero rows/columns if the algorithm's constraint is acceptable for your use case, then trim the result.","Rename expectations in tests: this function's contract is same-size square matrices only."],"exampleFix":"# before\nresult = matrix_multiply_recursive(a_2x3, b_3x3)  # ValueError\n\n# after\nfrom matrix.matrix_operation import multiply\nresult = multiply(a_2x3, b_3x3)  # general multiplication","handlingStrategy":"validation","validationCode":"from matrix.matrix_multiplication_recursion import is_square\n\nif not matrix_a or not matrix_b:\n    result = []\nelif len(matrix_a) != len(matrix_b) or not is_square(matrix_a) or not is_square(matrix_b):\n    raise ValueError(\"recursive multiply requires two equal-size square matrices\")\nelse:\n    result = matrix_multiply_recursive(matrix_a, matrix_b)","typeGuard":"def is_uniform_square_pair(a: list, b: list) -> bool:\n    \"\"\"Guard: both non-empty square nested lists of the same dimension.\"\"\"\n    return (\n        bool(a) and bool(b)\n        and isinstance(a, list) and isinstance(b, list)\n        and len(a) == len(b)\n        and all(len(r) == len(a) for r in a)\n        and all(len(r) == len(b) for r in b)\n    )","tryCatchPattern":"try:\n    result = matrix_multiply_recursive(a, b)\nexcept ValueError as e:\n    if \"Invalid matrix dimensions\" in str(e):\n        from matrix.matrix_operation import multiply\n        result = multiply(a, b)  # general algorithm handles compatible rectangles\n    else:\n        raise","preventionTips":["Reserve this function for equal-size square matrices; use the general multiply for everything else.","Pre-check with the module's own is_square() helper rather than reimplementing shape logic.","Pad rectangular matrices with zero rows/columns only if trimming the result is acceptable in your domain."],"tags":["matrix","recursion","square-matrix","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}