1.实现矩阵的相乘
part 1:矩阵相乘时,涉及到三重循环,并且在定义的矩阵乘法的函数中,加入非法输入检查,即矩阵相乘时,需前一个的行数等于后一个的列数,如果不符合,则返回空。
part 2: \r是回车,\n是换行,前者使光标到行首,后者使光标下移一格。
part 3:代码示例:
package demo3;
import java.util.Arrays;
public class MatrixMultiplication {
public static void main(String args[]) {
matrixMultiplicationTest();
}// Of main
public static int[][] multiplication(int[][] paraFirstMatrix, int[][] paraSecondMatrix) {
int m = paraFirstMatrix.length;
int n = paraFirstMatrix[0].length;
int p = paraSecondMatrix[0].length;
// Step 1. Dimension check. 矩阵尺寸检查
if (paraSecondMatrix.length != n) {
System.out.println("The two matrices cannot be multiplied.");
return null;
} // Of if
// Step 2. The loop.乘法循环
int[][] resultMatrix = new int[m][p];
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < n; k++) {
resultMatrix[i][j] += paraFirstMatrix[i][k] * paraSecondMatrix[k][j];
} // Of for k
} // Of for j
} // Of for i
return resultMatrix;
}// Of multiplication
// 矩阵乘法测试
public static void matrixMultiplicationTest() {
int[][] tempFirstMatrix = new int[2][3];
for (int i = 0; i < tempFirstMatrix.length; i++) {
for (int j = 0; j < tempFirstMatrix[0].length; j++) {
tempFirstMatrix[i][j] = i + j;
} // Of for j
} // Of for i
System.out.println("The first matrix is: \r\n" + Arrays.deepToString(tempFirstMatrix));
int[][] tempSecondMatrix = new int[3][2];
for (int i = 0; i < tempSecondMatrix.length; i++) {
for (int j = 0; j < tempSecondMatrix[0].length; j++) {
tempSecondMatrix[i][j] = i * 10 + j;
} // Of for j
} // Of for i
System.out.println("The second matrix is: \r\n" + Arrays.deepToString(tempSecondMatrix));
// 1乘以2
int[][] tempThirdMatrix = multiplication(tempFirstMatrix, tempSecondMatrix);
System.out.println("The third matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix));
// 第一个矩阵自身相乘测试
System.out.println("Trying to multiply the first matrix with itself.\r\n");
tempThirdMatrix = multiplication(tempFirstMatrix, tempFirstMatrix);
System.out.println("The result matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix));
}// Of matrixMultiplicationTest
}// MatrixMultiplication
代码运行结果: