Java学习-Day4

矩阵元素相加

一、矩阵的赋值

矩阵在计算机中表述为一个二维数组,可以想象为一个一维数组,但一维数组中每个位置存放的是一个数组。

初始化矩阵有两种方法:

1.静态初始化

程序员指定每个数组元素的初始值,系统决定数组长度。如下所示

1
int a[][] = {{1,2,3},{4,5,6},{7,8,9,10}};

2.动态初始化

程序员只指定数组长度,由系统为数组元素分配初始值。如下所示

1
2
int [][]array1 = new int[3][];
int [][]array2 = new int[3][2];

二、二重循环

第一重循环遍历行,第二重循环遍历当前行的所有列。分别遍历两个矩阵并设置一个新的矩阵用于存放两个矩阵的值就可以实现矩阵的相加。这里需要注意的是,两个相加的矩阵行和列必须相等。

三、具体实现

输入

两个相同大小的二维数组

输出

两个输入数组相同行列数值之和

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package test;

import java.util.Arrays;

/**
* This is the seventh code. Names and comments should follow my style strictly.
*
* @author ShiHuai Wen shihuaiwen@outlook.com.
*/
public class MatrixAddition {

/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
matrixElementSumTest();

matrixAdditionTest();
}// Of main

/**
*********************
* Sum the elements of a matrix.
*
* @param paraMatrix The given matrix.
* @return The sum of all its elements.
*********************
*/
public static int matrixElementSum(int[][] paraMatrix) {
int resultSum = 0;
for (int i = 0; i < paraMatrix.length; i++) {
for (int j = 0; j < paraMatrix[0].length; j++) {
resultSum += paraMatrix[i][j];
} // Of for j
} // Of for i

return resultSum;
}// Of matrixElementSum

/**
*********************
* Unit test for respective method.
*********************
*/
public static void matrixElementSumTest() {
int[][] tempMatrix = new int[3][4];
for (int i = 0; i < tempMatrix.length; i++) {
for (int j = 0; j < tempMatrix[0].length; j++) {
tempMatrix[i][j] = i * 10 + j;
} // Of for j
} // Of for i

System.out.println("The matrix is: \r\n" + Arrays.deepToString(tempMatrix));
System.out.println("The matrix element sum is: " + matrixElementSum(tempMatrix) + "\r\n");
}// Of matrixElementSumTest

/**
*********************
* Add two matrices. Attention: NO error check is provided at this moment.
*
* @param paraMatrix1 The first matrix.
* @param paraMatrix2 The second matrix. It should have the same size as
* the first one's.
* @return The addition of these matrices.
*********************
*/
public static int[][] matrixAddition(int[][] paraMatrix1, int[][] paraMatrix2) {
int[][] resultMatrix = new int[paraMatrix1.length][paraMatrix1[0].length];

for (int i = 0; i < paraMatrix1.length; i++) {
for (int j = 0; j < paraMatrix1[0].length; j++) {
resultMatrix[i][j] = paraMatrix1[i][j] + paraMatrix2[i][j];
} // Of for j
} // Of for i

return resultMatrix;
}// Of matrixAddition

/**
*********************
* Unit test for respective method.
*********************
*/
public static void matrixAdditionTest() {
int[][] tempMatrix = new int[3][4];
for (int i = 0; i < tempMatrix.length; i++) {
for (int j = 0; j < tempMatrix[0].length; j++) {
tempMatrix[i][j] = i * 10 + j;
} // Of for j
} // Of for i

System.out.println("The matrix is: \r\n" + Arrays.deepToString(tempMatrix));
int[][] tempNewMatrix = matrixAddition(tempMatrix, tempMatrix);
System.out.println("The new matrix is: \r\n" + Arrays.deepToString(tempNewMatrix));
}// Of matrixAdditionTest

}// Of class MatrixAddition

运行截图

矩阵相乘

一、三重循环

三重循环是多数程序的极限。并不是说超过之后就会导致程序崩溃,而是这将导致运行时间按指数级别上升,一点时间变换都会产生明显的延迟。当算法需要使用更多重循环的时候就应该考虑是否有更优解。

二、非法输入检查

非法输入检查是程序正常运行的基本保障。如果检查所有的非法输入, 会导致大量代码行, 这在商业代码中是必须的。 如果需要测试代码,使用if-else不是一个明智的选择。这时可以考虑使用assert来定位和测试。

三、具体实现

矩阵相乘公式

\[ resultMatrix(i,j) = \sum_{k=0}^n paraFirstMatrix(i,k) * paraSecondMatrix(k,j) \]

输入

一个矩阵和一个与前个矩阵的转置大小相同的矩阵。

输出

符合输入规范则输出两矩阵相乘所得矩阵

不符合输入规范则输出为null

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package test;

import java.util.Arrays;

/**
* This is the eighth code. Names and comments should follow my style strictly.
*
* @author ShiHuai Wen shihuaiwen@outlook.com.
*/
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;

// 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

/**
*********************
* 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[][] 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

}// Of class MatrixMultiplication

运行截图

总结

不过是对二维数组进行简单的操作。需要注意的是错误检测,这在我写代码的大多数时候都不会在意。尤其是刷算法题的时候,常常对数据结构判空忽略,直到题目没有AC时才恍然大悟。算是一个不太好的习惯吗,需要改进。