使用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("矩阵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("矩阵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("两个矩阵的乘积为:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
输出结果
矩阵A:5 2 3
2 6 3
6 9 1
矩阵B:
2 7 5
1 4 3
1 2 1
两个矩阵的乘积为:
15 49 34
13 44 31
22 80 58
以上是 使用Java将两个矩阵相乘 的全部内容, 来源链接: utcz.com/z/359611.html