模板代码:
package com.DJL.ArraysMatrix;
import java.util.Arrays;
public class 矩阵运算 {
static long[][] matrixMultiply(long[][] m1, long[][] m2) {
int n = m1.length;
int m = m1[0].length;
if (m != m2.length) {
throw new IllegalArgumentException();
}
long[][] result = new long[n][m2[0].length];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m2[0].length; j++) {
for (int k = 0; k < m; k++) {
result[i][j] += m1[i][k] * m2[k][j];
}
}
}
return result;
}
static void print(long[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
System.out.println(Arrays.toString(matrix[i]));
}
}
public static void main(String[] args) {
long[][] a = {{1, 0, 3, -1}, {2, 1, 0, 2}};
long[][] b = {{4, 1, 0}, {-1, 1, 3}, {2, 0, 1}, {1, 3, 4}};
long[][] result = matrixMultiply(a, b);
print(result);
}
}
运行结果:[9, -2, -1]
[9, 9, 11]