File tree Expand file tree Collapse file tree
src/main/java/com/thealgorithms/matrix Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments