Java 二维矩阵中一维阵列中心坐标的求法
以下是场景:Java 二维矩阵中一维阵列中心坐标的求法,java,math,Java,Math,以下是场景: // getMatrix() returns int[]. It is 1-d // I wish it was 2d. int[] mat = MyMatrix.getMatrix(); // get height and width of the matrix; int h = MyMatrix.height; int w = MyMatrix.width; // calculate the center index of the matrix int c = ... //
// getMatrix() returns int[]. It is 1-d
// I wish it was 2d.
int[] mat = MyMatrix.getMatrix();
// get height and width of the matrix;
int h = MyMatrix.height;
int w = MyMatrix.width;
// calculate the center index of the matrix
int c = ... // need help here
// manipulate the center element of the matrix.
SomeClass.foo(mat[c]);
示例:假设我有一个5 x 5的矩阵:
* * * * * // index 0 to 4
* * * * * // index 5 to 9
* * * * * // index 10 to 14.
* * * * * // index 15 to 19
* * * * * // index 20 to 24
如果getMatrix()
返回int[][]
,则该矩阵的中心坐标将基于(2,2)
0索引。但是由于getMatrix()
返回int[]
,因此中心坐标索引c
是12
但是,如果矩阵的高度或宽度为偶数,则中心索引可以是其2个或4个中心之一,如6 x 6矩阵所示:
* * * * * *
* * * * * *
* * @ @ * *
* * @ @ * *
* * * * * *
* * * * * *
-->中心是上面的任何一个@
如何计算m x n矩阵的中心索引
c
?矩阵的中心是数组的中心。这是因为中心行上方和下方的行数相等。在中心行,中心单元格的左右两侧将有相等数量的单元格
int c = mat.length / 2;
或者,如果您愿意:
int c = (width * height) / 2;
这假设矩阵只有一个中心。也就是说,行和列的数量是奇数
如果需要中间值(所有中心的平均值),它将变得更加复杂:
int x1 = (width - 1)/2;
int x2 = width/2;
int y1 = (height - 1)/2;
int y2 = height/2;
double median = (mat[width*y1 + x1] + mat[width*y1 + x2] +
mat[width*y2 + x1] + mat[width*y2 + x2])*0.25;
如果您只需要一个中心单元格,请从x1
、x2
、y1
、y2
四种组合中选择一种。最简单的是:
int c = width * (height / 2) + (width / 2); // lower right center
我想可能有比我现在做的更简单的解决办法。你不需要取整吗?如果矩阵是6 x 6,这将失败。这将得到c=18,它不在中心。6x6/2=18。中心应该是以下任意一个:15、16、21和22。@ChristianMann,5x5矩阵有25个单元。25/2=12(整数除法),这是寻求的索引。它仅适用于奇数x奇数矩阵,而不适用于偶数x奇数或奇数x偶数或偶数x偶数矩阵。顺便说一下,我不需要中间值。我只需要以1d索引表示的中心坐标。@MizardX edit:在10 x 5矩阵上,这将失败。10 x 5矩阵的中心是(以0指数为基础):24或25。你的答案是22。