Skip to content

Commit fcfd803

Browse files
committed
MatrixMultiplication.java created and updated.
1 parent 5c6d3c3 commit fcfd803

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.thealgorithms.matrix;
2+
3+
public class MatrixMultiplication {
4+
private MatrixMultiplication() {
5+
}
6+
7+
/**
8+
* Multiplies two matrices.
9+
*
10+
* @param matrixA the first matrix rowsA x colsA
11+
* @param matrixB the second matrix rowsB x colsB
12+
* @return the product of the two matrices rowsA x colsB
13+
* @throws IllegalArgumentException if the matrices cannot be multiplied
14+
*/
15+
public static double[][] multiply(double[][] matrixA, double[][] matrixB) {
16+
17+
if (matrixA == null || matrixB == null) {
18+
throw new IllegalArgumentException("Input matrices cannot be null");
19+
}
20+
21+
if (matrixA[0].length != matrixB.length) {
22+
throw new IllegalArgumentException("Matrices cannot be multiplied: incompatible dimensions.");
23+
}
24+
25+
int rowsA = matrixA.length;
26+
int colsA = matrixA[0].length;
27+
int colsB = matrixB[0].length;
28+
29+
double[][] result = new double[rowsA][colsB];
30+
31+
for (int i = 0; i < rowsA; i++) {
32+
for (int j = 0; j < colsB; j++) {
33+
for (int k = 0; k < colsA; k++) {
34+
result[i][j] += matrixA[i][k] * matrixB[k][j];
35+
}
36+
}
37+
}
38+
return result;
39+
}
40+
}

0 commit comments

Comments
 (0)