扩展我的评论,您应该能够如下计算重心:
foreach col
foreach row
massvector.x += matrix[col][row] * col
massvector.y += matrix[col][row] * row
totalmass += matrix[col][row]
massvector.x /= totalmass
massvector.y /= totalmass
该想法基于https://en.wikipedia.org/wiki/Center_of_mass中的“粒子系统”部分:将矩阵元素视为在2D平面上布置的等距粒子.每个元素的位置等于其在矩阵中的位置,即列和行,而粒子质量是该单元格/元素/矩阵位置的值.
使用您的(现在已删除)测试用例的示例实现:
double[][] matrix = new double[][]{
{0.70,0.75,0.70,0.75,0.80},
{0.55,0.30,0.20,0.10,0.70},
{0.80,0.10,0.00,0.00,0.80},
{0.70,0.00,0.00,0.00,0.80},
{0.80,0.90,0.80,0.75,0.90}};
double cx = 0;
double cy = 0;
double m = 0;
for(int x = 0; x < matrix.length; x++ ) {
for(int y = 0; y < matrix[x].length; y++) {
cx += matrix[x][y] * x;
cy += matrix[x][y] * y;
m += matrix[x][y];
}
}
//those are center's the cell coordinates within the matrix
int cmx = (int)(cx/m);
int cmy = (int)(cy/m);
//whatever you'd need that value for (the position is more likely what you're after)
double centerOfMassValue = matrix[cmx][cmy];
上面的示例将以5×5矩阵的中心返回坐标2/2.