JAVA学习(小白向)—矩阵相乘—2021-05-27
矩阵乘法的定义
代码如下:
package a8;
import java.util.Arrays;
/**
*
* @author hengyuzuo
*
*/
public class MatrixM {
/**
* **********************
* The entrance of the program.
*
* @param args Not used now.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
matrixMultiplicationTest();
}// Of main
/**
* **********************
* Unit test for respective method.
* **********************
*/
public static void matrixMultiplicationTest() {
int[][] tempMatrix1 = new int[2][3];
for (int i = 0; i < tempMatrix1.length; i++) {
for (int j =0; j < tempMatrix1[0].length; j++) {
tempMatrix1[i][j] = i + j;
/**
* 0.1.2
* 1.2.3
*
*/
}// Of for j
}// Of for i
System.out.println("The first matrix is: " + Arrays.deepToString(tempMatrix1));
int[][] tempMatrix2 = new int[3][4];
for (int i = 0; i < tempMatrix2.length; i++) {
for (int j =0; j < tempMatrix2[0].length; j++) {
tempMatrix2[i][j] = i * 2 + j;
/**
* 0.1.2.3
* 2.3.4.5
* 4.5.6.7
*
*/
}// Of for j
}// Of for i
System.out.println("The Second matrix is: " + Arrays.deepToString(tempMatrix2));
int[][] tempMatrix3 = multiplication(tempMatrix1, tempMatrix2);
System.out.println("The Third matrix is: " + Arrays.deepToString(tempMatrix3));
System.out.println("Trying to multiply the first matrix with itself.");
tempMatrix3 =multiplication(tempMatrix1, tempMatrix1);
System.out.println("The matrix multiply with itself is: " + Arrays.deepToString(tempMatrix3));
}// Of matrixMultiplicationTest
/**
* *************************************
* Matrix multiplication
* @param paraMatrix1
* @param paraMatrix2
* @return the result matrix of multiplication
* *************************************
*/
public static int[][] multiplication(int[][] paraMatrix1, int[][] paraMatrix2) {
// TODO Auto-generated method stub
int m = paraMatrix1.length;
int n = paraMatrix1[0].length;
int p = paraMatrix2[0].length;
//Step1.Dimension check
if (paraMatrix2.length != n) {
System.out.println("The two matrices cannot be multiplied.");
return null;
}// Of if
//Step2. The loop
int[][] resultMatrix = new int[m][n];
for (int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
for(int k =0; k<n; k++) {
resultMatrix[i][j] += paraMatrix1[i][k] *paraMatrix2[k][j];
}// Of for k
}// Of for j
}// Of for k
return resultMatrix;
}// Of multiplication
}// Of class
运行结果:
The first matrix is: [[0, 1, 2], [1, 2, 3]]
The Second matrix is: [[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7]]
The Third matrix is: [[10, 13, 16], [16, 22, 28]]
Trying to multiply the first matrix with itself.
The two matrices cannot be multiplied.
The matrix multiply with itself is: null
public static不知何时用int,何时用void、等?