{"record":{"id":"2ee6ba934580aa84","repo":"TheAlgorithms/Java","slug":"matrices-cannot-be-multiplied-incompatible-dimens","errorCode":null,"errorMessage":"Matrices cannot be multiplied: incompatible dimensions.","messagePattern":"Matrices cannot be multiplied: incompatible dimensions\\.","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/matrix/MatrixMultiplication.java","lineNumber":49,"sourceCode":"     * @param matrixA the first matrix rowsA x colsA\n     * @param matrixB the second matrix rowsB x colsB\n     * @return the product of the two matrices rowsA x colsB\n     * @throws IllegalArgumentException if the matrices cannot be multiplied\n     */\n    public static double[][] multiply(double[][] matrixA, double[][] matrixB) {\n        // Check the input matrices are not null\n        if (matrixA == null || matrixB == null) {\n            throw new IllegalArgumentException(\"Input matrices cannot be null\");\n        }\n\n        // Check for empty matrices\n        if (matrixA.length == 0 || matrixB.length == 0 || matrixA[0].length == 0 || matrixB[0].length == 0) {\n            throw new IllegalArgumentException(\"Input matrices must not be empty\");\n        }\n\n        // Validate the matrix dimensions\n        if (matrixA[0].length != matrixB.length) {\n            throw new IllegalArgumentException(\"Matrices cannot be multiplied: incompatible dimensions.\");\n        }\n\n        int rowsA = matrixA.length;\n        int colsA = matrixA[0].length;\n        int colsB = matrixB[0].length;\n\n        // Initialize the result matrix with zeros\n        double[][] result = new double[rowsA][colsB];\n\n        // Perform matrix multiplication\n        for (int i = 0; i < rowsA; i++) {\n            for (int j = 0; j < colsB; j++) {\n                for (int k = 0; k < colsA; k++) {\n                    result[i][j] += matrixA[i][k] * matrixB[k][j];\n                }\n            }\n        }\n        return result;","sourceCodeStart":31,"sourceCodeEnd":67,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/matrix/MatrixMultiplication.java#L31-L67","documentation":"Thrown by MatrixMultiplication.multiply when matrixA's column count (matrixA[0].length) does not equal matrixB's row count (matrixB.length). Matrix multiplication A x B is only defined when cols(A) == rows(B); otherwise the inner k-loop would index out of bounds, so the guard rejects the operation with a clear message.","triggerScenarios":"Call multiply on a 2x3 matrix A and a 2x4 matrix B (cols(A)=3 != rows(B)=2). Common with transposed operands, swapped argument order, or data loaded with rows/columns inverted.","commonSituations":"Transposing one matrix but not the other, passing (B, A) instead of (A, B), CSV loaded as row-major when the algorithm expects column-major, or a refactor that changed orientation.","solutions":["Verify matrixA[0].length == matrixB.length before calling; transpose one operand if needed.","Log both shapes at the call site to diagnose mismatches quickly.","Wrap multiplication in a helper that documents the cols(A)==rows(B) contract."],"exampleFix":"// before\ndouble[][] r = MatrixMultiplication.multiply(a, b);\n\n// after\nif (a[0].length != b.length) {\n    // transpose b or swap operands as appropriate\n    b = MatrixTranspose.doubleTranspose(b); // your transpose helper\n}\ndouble[][] r = MatrixMultiplication.multiply(a, b);","handlingStrategy":"validation","validationCode":"if (matrixA[0].length != matrixB.length) {\n    throw new IllegalArgumentException(\n        \"cols(A)=\" + matrixA[0].length + \" must equal rows(B)=\" + matrixB.length);\n}\ndouble[][] r = MatrixMultiplication.multiply(matrixA, matrixB);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Log both shapes at the call site to diagnose transposition/order mistakes fast.","Keep a single helper for 'can multiply' checks and reuse it before every multiply call."],"tags":["matrix","linear-algebra","dimension-mismatch","argument-validation"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}