.利用二维数组编程实现矩阵相乘、矩阵转置Java源代码
时间: 2023-06-05 16:08:01 浏览: 141
java 矩阵转置的代码
5星 · 资源好评率100%
好的,请稍等...
以下是使用 Java 编写的二维数组实现矩阵相乘与矩阵转置的源代码:
矩阵相乘:
```
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] matrixA = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrixB = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int[][] result = multiply(matrixA, matrixB);
printMatrix(result);
}
public static int[][] multiply(int[][] matrixA, int[][] matrixB) {
int aRows = matrixA.length;
int aCols = matrixA[0].length;
int bRows = matrixB.length;
int bCols = matrixB[0].length;
if (aCols != bRows) {
throw new IllegalArgumentException("The number of columns in matrix A must equal the number of rows in matrix B!");
}
int[][] result = new int[aRows][bCols];
for (int i = 0; i < aRows; i++) {
for (int j = 0; j < bCols; j++) {
for (int k = 0; k < aCols; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
```
矩阵转置:
```
public class MatrixTranspose {
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] result = transpose(matrix);
printMatrix(result);
}
public static int[][] transpose(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int[][] result = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
```
希望能帮到你!
阅读全文