3

给定一个二维数组,我需要想出一个输出质心的算法。我想出了下面的算法,但是,当数组大小增加到 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;

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

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

4

3 回答 3

2

扩展我的评论,您应该能够按如下方式计算质心:

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

上面的示例将返回坐标 2/2,其中是 5x5 矩阵的中心。

于 2016-03-17T15:16:15.207 回答
1

你需要做一个加权平均,所以对于一个 3x3 数组,

x̄= (质量(col1)*1 + 质量(col2)*2 + 质量(col3)*3) / (质量(col1) + 质量(col2) + 质量(col3))

同样对于 y 用行替换列。

一旦你有了这两个值,它们就会告诉你阵列质心的 x 和 y 坐标。

如果您需要视觉示例,请参阅以下链接中的示例一:http ://www.batesville.k12.in.us/physics/APPhyNet/Dynamics/Center%20of%20Mass/2D_1.html

于 2016-03-17T15:16:49.597 回答
0

我假设由于您将权重存储在矩阵中,因此矩阵中的位置将对应于列索引为x行索引为y的权重坐标。因此,row=2,col=3 处的权重我们将在 x/y 坐标系上取为 (3,2)。

此代码遵循Wikipedia上粒子系统的质心解决方案:

public static Point2D.Double getCenterOfMass( double[][] matrix) {
    double massTotal = 0;
    double xTotal = 0;
    double yTotal = 0;
    for (int rowIndex = 0; rowIndex < matrix.length; rowIndex++) {
        for (int colIndex = 0; colIndex < matrix[0].length; colIndex++) {
            massTotal += matrix[rowIndex][colIndex];
            xTotal += matrix[rowIndex][colIndex] * colIndex;
            yTotal += matrix[rowIndex][colIndex] * rowIndex;
        }
    }
    xTotal /= massTotal;
    yTotal /= massTotal;
    return new Point2D.Double(xTotal,yTotal);
}

完整的工作代码在这里

于 2016-03-17T17:14:05.550 回答