Reputation: 6038
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()
were to return int[][]
, the center coordinate of this matrix would be (2,2)
0-index based. But since getMatrix()
returns int[]
, the center coordinate index c
is 12
.
However, if the height or width of the matrix is even, the center index can one of its 2 or 4 centers as shown in a 6 x 6 matrix:
* * * * * *
* * * * * *
* * @ @ * *
* * @ @ * *
* * * * * *
* * * * * *
--> The center is any of the @
above.
How would I calculate for the center index c
of an m x n matrix?
Upvotes: 5
Views: 8927
Reputation: 89241
The center of the matrix is the center of the array. This is because there will be an equal number of rows above and below the center row. And on 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 assumes that there is a single center of the matrix. That is, there is an odd number of rows and columns.
If you want the median (mean of all centers), it will become more complicated:
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 only need one of the center cells, pick one of the four combinations of x1
,x2
,y1
,y2
. Simplest would be:
int c = width * (height / 2) + (width / 2); // lower right center
Upvotes: 7