java实现矩阵相乘

时间:2020-11-28 14:09:06

众所周知,矩阵的乘法就是矩阵的行列相乘再相加。话不多说,直接上代码:

package test;


public class matrixMultiply {

public static void printMatrix(int[][] a, int[][] b) {
int r = a.length;
int c = b[0].length;
double result[][] = new double[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
int temp = 0;
for (int k = 0; k < b.length; k++) {
temp += a[i][k] * b[k][j];
}
result[i][j] = temp;
}
}
System.out.println("矩阵相乘的结果为: ");
for (int m = 0; m < r; m++) {
for (int n = 0; n < c; n++) {
System.out.print(result[m][n] + "\t");
}
System.out.println();
}
}


public static void main(String[] args) {
int[][] a = { { 1, 2 }, { 3, 4 }, { 5, 6 } };// 自己定义矩阵
int[][] b = { { 1, 2, 3 }, { 4, 5, 6 } };// 自己定义矩阵
printMatrix(a, b);
}
}

结果为:

9.0 12.0   15.0
19.0 26.0 33.0
29.0 40.0 51.0