java实现矩阵乘法(附完整源码)
时间: 2023-10-17 22:10:14 浏览: 118
以下是Java实现矩阵乘法的完整代码:
```java
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] matrixA = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrixB = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};
int[][] result = multiplyMatrices(matrixA, matrixB);
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
public static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB) {
int rowsA = matrixA.length;
int columnsA = matrixA[0].length;
int rowsB = matrixB.length;
int columnsB = matrixB[0].length;
if (columnsA != rowsB) {
throw new IllegalArgumentException("Cannot multiply matrices. Incorrect dimensions.");
}
int[][] result = new int[rowsA][columnsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < columnsB; j++) {
for (int k = 0; k < columnsA; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
}
```
在此示例中,我们定义了两个矩阵`matrixA`和`matrixB`,并将它们传递给`multiplyMatrices`方法。该方法使用嵌套的for循环计算矩阵乘积,并将结果存储在一个新的矩阵`result`中。最后,我们在控制台上打印结果。
阅读全文