How to get the coordinate of the center of an array of size 1 in a 2d matrix

Here is the scenario:

// 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]); 

Example: suppose I have a 5 x 5 matrix:

 * * * * * // index 0 to 4 * * * * * // index 5 to 9 * * * * * // index 10 to 14. * * * * * // index 15 to 19 * * * * * // index 20 to 24 

If getMatrix() should have returned int[][] , the center coordinate of this matrix would be (2,2) 0-index. But since getMatrix() returns int[] , the center coordinate index c is 12 .

However, if the height or width of the matrix is โ€‹โ€‹even, the central index can be one of its 2 or 4 centers, as shown in the 6 x 6 matrix:

 * * * * * * * * * * * * * * @ @ * * * * @ @ * * * * * * * * * * * * * * 

-> Center is any of the @ above.

How would I calculate the center index c matrix mxn ?

+4
source share
1 answer

The center of the matrix is โ€‹โ€‹the center of the array. This is due to the fact that there will be an equal number of lines above and below the center line. And in the center row there will be an equal number of cells to the left and right of the center cell.

 int c = mat.length / 2; 

or if you want:

 int c = (width * height) / 2; 

This suggests that there is a single center of the matrix. That is, there is an odd number of rows and columns.

If you need an average (average of all centers), it will become more complex:

 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; 

If you need only one of the central cells, select one of the four combinations x1 , x2 , y1 , y2 . The simplest would be:

 int c = width * (height / 2) + (width / 2); // lower right center 
+7
source

Source: https://habr.com/ru/post/1381359/


All Articles