代码来自闵老师”日撸Java三百行(01-10天,基本语法),原文链接:“https://blog.csdn.net/minfanphd/article/details/116933803
矩阵相乘
/……/是对程序进行多行注释,/**…*/也是对程序进行多行注释。区别在于生成的javadoc文档不会出现前者注释的内容,而后者注释的内容会出现在生成的javadoc文档中。//符号是用来进行单行注释的。
package basic;
import java.util.Arrays;
import java.util.PrimitiveIterator.OfDouble;
/**
* This is the eighth code. Names and comments are followed original code strictly.
*
* @author WX873
*
*/
public class MatrixMultiplication {
/*****************************************
* The entrance of the program.
*
* param args not used now.
* ***************************************
*/
public static void main(String args[]) {
matrixMultiplicationTest();
}//of main
/**
* Matrix multiplication. The columns of the first matrix should be equal to the rows
* of the second one.
*
* @param paraFirstMatrix The first matrix.
* @param paraSecondMatrix The second matrix.
* @return The result matrix.
*/
public static int[][] multiplication(int[][] paraFirstMatrix, int[][] paraSecondMatrix) {
int m = paraFirstMatrix.length;
int n = paraFirstMatrix[0].length;
int p = paraSecondMatrix[0].length;
int[][] resultMtrix = new int[m][p];
//step 1. Dimension check.
if (paraSecondMatrix.length != n) {
System.out.println("The two matrix cannot multiplied");
}//of if
//step 2. the loop.
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < resultMtrix.length; k++) {
resultMtrix[i][j] = paraFirstMatrix[i][k]*paraSecondMatrix[k][j];
}// of for k
}//of for p
}//of for i
return resultMtrix;
}//of multiplication
/**
* ******************************************
* Unit test for respective method.
* ******************************************
*/
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));
int[][] resultMatrix = multiplication(tempFirstMatrix, tempSecondMatrix);
System.out.println("The result matrix is:\r\n" + Arrays.deepToString(resultMatrix));
resultMatrix = multiplication(tempFirstMatrix, tempFirstMatrix);
System.out.println("The result matrix is:\r\n" + Arrays.deepToString(resultMatrix));
}//of matrixMultiplicationTest
}//of class MatrixMultiplication
本代码按照原文章呈现,最终运算结果如下图。发现结果作为结果输出的矩阵并不为空。而是为[[1,2,3],[2,4,6]],也就是说依然对矩阵进行了乘法运算。运算结果依然是行列相乘,每一轮循环第二个矩阵有几行就进行几个数的相乘。
可以对代码进行如上图修改,用if-else语句进行分支选择,这样传入行列式不能相乘时将不进行运算。运行结果如下: