利用 Java 乘以两个矩阵
矩阵乘法通过乘以 2 个矩阵生成一个新矩阵。但这仅在第一个矩阵的列等于第二个矩阵的行时才有可能。如下给出使用方块矩阵的矩阵乘法示例。
示例
public class Example { public static void main(String args[]) { int n = 3; int[][] a = { {5, 2, 3}, {2, 6, 3}, {6, 9, 1} }; int[][] b = { {2, 7, 5}, {1, 4, 3}, {1, 2, 1} }; int[][] c = new int[n][n]; System.out.println("Matrix A:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } System.out.println("Matrix B:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(b[i][j] + " "); } System.out.println(); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++){ for (int k = 0; k < n; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } } System.out.println("The product of two matrices is:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(c[i][j] + " "); } System.out.println(); } } }
输出
Matrix A: 5 2 3 2 6 3 6 9 1 Matrix B: 2 7 5 1 4 3 1 2 1 The product of two matrices is: 15 49 34 13 44 31 22 80 58
广告