如何在2d矩阵中得到1维数组的中心坐标

Nei*_*val 4 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 = ... // need help here

// manipulate the center element of the matrix.
SomeClass.foo(mat[c]);
Run Code Online (Sandbox Code Playgroud)

示例:假设我有一个5 x 5矩阵:

* * * * * // index 0 to 4
* * * * * // index 5 to 9
* * * * * // index 10 to 14.
* * * * * // index 15 to 19
* * * * * // index 20 to 24
Run Code Online (Sandbox Code Playgroud)

如果getMatrix()要返回int[][],则该矩​​阵的中心坐标将(2,2)基于0指数.但是自从getMatrix()返回以来int[],中心坐标指数c12.

但是,如果矩阵的高度或宽度是偶数,则中心索引可以是2或4个中心之一,如6 x 6矩阵所示:

* * * * * *
* * * * * *
* * @ @ * *
* * @ @ * *
* * * * * *
* * * * * *
Run Code Online (Sandbox Code Playgroud)

- >中心是@上述任何一个.

我将如何计算为中心指数c的的m×n矩阵

Mar*_*rot 7

矩阵的中心是阵列的中心.这是因为在中心行的上方和下方将有相同数量的行.在中心行,中心单元的左侧和右侧将有相同数量的单元格.

int c = mat.length / 2;
Run Code Online (Sandbox Code Playgroud)

或者,如果你想:

int c = (width * height) / 2;
Run Code Online (Sandbox Code Playgroud)

这假设矩阵有一个中心.也就是说,存在奇数个行和列.

如果你想要中位数(所有中心的平均值),它将变得更加复杂:

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;
Run Code Online (Sandbox Code Playgroud)

如果你只需要中心的细胞之一,挑选的四种组合之一x1,x2,y1,y2.最简单的是:

int c = width * (height / 2) + (width / 2); // lower right center
Run Code Online (Sandbox Code Playgroud)