矩阵是一个二维数组。因此,矩阵矩阵是一个 4D 数组。
所以 2x2 矩阵的 3x2 矩阵将是:
int[][][][] matrixOfMatrices = new int[3][2][2][2];
至于如何打印,这里举个例子:
int outerHeight = 3, outerWidth = 2, innerHeight = 2, innerWidth = 2;
int[][][][] matrixOfMatrices = new int[outerHeight][outerWidth][innerHeight][innerWidth];
// Fill with some data
for (int i = 1, outRow = 0; outRow < outerHeight; outRow++)
for (int outCol = 0; outCol < outerWidth; outCol++)
for (int inRow = 0; inRow < innerHeight; inRow++)
for (int inCol = 0; inCol < innerWidth; inCol++)
matrixOfMatrices[outRow][outCol][inRow][inCol] = i++;
// Print 2D x 2D matrix
int numWidth = Integer.toString(outerHeight * outerWidth * innerHeight * innerWidth + 1).length();
for (int outRow = 0; outRow < outerHeight; outRow++) {
if (outRow != 0) {
for (int outCol = 0; outCol < outerWidth; outCol++) {
if (outCol != 0)
System.out.print("-+-");
System.out.print("-".repeat(innerWidth * (numWidth + 1) - 1));
}
System.out.println();
}
for (int inRow = 0; inRow < innerHeight; inRow++) {
for (int outCol = 0; outCol < outerWidth; outCol++) {
if (outCol != 0)
System.out.print(" | ");
for (int inCol = 0; inCol < innerWidth; inCol++) {
if (inCol != 0)
System.out.print(" ");
System.out.printf("%" + numWidth + "d", matrixOfMatrices[outRow][outCol][inRow][inCol]);
}
}
System.out.println();
}
}
输出
1 2 | 5 6
3 4 | 7 8
------+------
9 10 | 13 14
11 12 | 15 16
------+------
17 18 | 21 22
19 20 | 23 24
查看不同尺寸的打印结果:
int outerHeight = 2, outerWidth = 3, innerHeight = 4, innerWidth = 5;
输出
1 2 3 4 5 | 21 22 23 24 25 | 41 42 43 44 45
6 7 8 9 10 | 26 27 28 29 30 | 46 47 48 49 50
11 12 13 14 15 | 31 32 33 34 35 | 51 52 53 54 55
16 17 18 19 20 | 36 37 38 39 40 | 56 57 58 59 60
--------------------+---------------------+--------------------
61 62 63 64 65 | 81 82 83 84 85 | 101 102 103 104 105
66 67 68 69 70 | 86 87 88 89 90 | 106 107 108 109 110
71 72 73 74 75 | 91 92 93 94 95 | 111 112 113 114 115
76 77 78 79 80 | 96 97 98 99 100 | 116 117 118 119 120