-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathMatrixMultiplication_Passing_Matrix_Function.java
47 lines (39 loc) · 1.45 KB
/
MatrixMultiplication_Passing_Matrix_Function.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Java Program to Multiply two Matrices by Passing Matrix to a Function
// p4n.in
// codeswithpankaj.com
public class MatrixMultiplication_Passing_Matrix_Function {
public static void main(String[] args) {
// Define the matrices
int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
// Perform matrix multiplication
int[][] productMatrix = multiplyMatrices(matrix1, matrix2);
// Display the result
System.out.println("Product of the matrices:");
displayMatrix(productMatrix);
}
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int rows1 = matrix1.length;
int columns1 = matrix1[0].length;
int columns2 = matrix2[0].length;
int[][] result = new int[rows1][columns2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
for (int k = 0; k < columns1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
public static void displayMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}