编程语言
首页 > 编程语言> > java-矩阵的质心

java-矩阵的质心

作者:互联网

给定2D数组,我需要提出一种输出质心的算法.我在下面提出了算法,但是,当数组大小增加到10 x 10矩阵时,它会产生不正确的解决方案.我使用Java编写并运行了该算法.我没有在这里提供代码,只是对我的算法进行了解释,因为我认为这是不正确的.但是,我无法找到原因.

Store into an array: Mean of each row
Store into an array: Mean of each column

The algo below is used for row and column:
Loop through the row array,
if(row = 1){
value = (mean of row 1) - (mean of row 2 + mean of row 3+ mean of row 4)
}else if(row =Length of array){
value = (mean of row 1 + mean of row 2 + mean of row 3) - (mean of row 4)}
else{
value = (mean of rows until ith row) - (ith row till end of array)
}
final value = lowest value;

我知道应该处理行和列的均值.因此,在我的算法中,我找出行和列的均值,然后进行上面所示的计算.相同的算法适用于列.

任何和所有帮助表示赞赏.也许,我对质心的理解不正确.如果不清楚,请询问.这是我自己的算法,是根据我对质心的理解而创建的,因此如果不清楚,请提出.谢谢!

解决方法:

扩展我的评论,您应该能够如下计算重心:

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.

标签:centroid,java,algorithm
来源: https://codeday.me/bug/20191118/2031917.html