2013-09-26 52 views
4

如何从多维数组中挑选出一些值,然后计算平均选定值?因此,当我点击一些图像时,它应该不仅在鼠标指针所在的位置显示深度数据(来自Microsoft Kinect),还应该计算环境中的值(这是多维数组)。Sum多维数组C#

这是我的代码:

protected void imageIR_MouseClick(object sender, System.Windows.Input.MouseEventArgs e) 
    { 
     // Get the x and y coordinates of the mouse pointer. 
     System.Windows.Point mousePoint = e.GetPosition(imageIR); 
     double xpos_IR = mousePoint.X; 
     double ypos_IR = mousePoint.Y; 
     int x = (int)xpos_IR; 
     int y = (int)ypos_IR; 
     lbCoord.Content = "x- & y- Koordinate [pixel]: " + x + " ; " + y; 
     int d = (ushort)pixelData[x + y * this.depthFrame.Width]; 
     d = d >> 3; 
     int xpos_Content = (int)((x - 320) * 0.03501/2 * d/10); 
     int ypos_Content = (int)((240 - y) * 0.03501/2 * d/10); 
     xpos.Content = "x- Koordinate [mm]: " + xpos_Content; 
     ypos.Content = "y- Koordinate [mm]: " + ypos_Content; 
     zpos.Content = "z- Koordinate [mm]: " + (d); 

     // Allocating array size 
     int i = 10; 
     int[] x_array = new int[i]; 
     int[] y_array = new int[i]; 
     int[,] d_array = new int[i,i]; 

     for (int m = 0; m < 10; m++) 
     { 
      for (int n = 0; n < 10; n++) 
      { 
       x_array[m] = x + m; 
       y_array[n] = y + n; 
       d_array[m, n] = (ushort)pixelData[x_array[m] + y_array[n] * this.depthFrame.Width]; 
       d_array[m, n] = d_array[m, n] >> 3; 
      } 
     } 
    } 

所以,第一:我怎么总结从d_array所有值[M,N]?是否可以计算每一行的总和( - >一维数组/矢量),然后再次计算列的总和( - >零维数组/标量)?

+0

你可以使用这个帖子中的答案扁平化多维数组http://stackoverflow.com/questions/1590723/flatten-list-in-linq。你可以使用linq来计算平均值以及http://csharp.net-tutorials.org/linq-to-objects/linq-average/csharp-c-linq-average-example/。 –

+1

您可以在锯齿阵列上选择“SelectMany”,而不是多维阵列。 –

回答

13

所以,第一:如何从d_array总结所有的值[M,N]

您可以使用:

int sum = d_array.Cast<int>().Sum(); 

这将自动展开了多维数组和取所有元素的总和。

是否有可能计算每行( - >一维数组/矢量)的总和,然后再次计算列的总和( - >零维数组/标量)?

是的,但这需要手动循环。有没有简单的一个班轮这一点,虽然这将是很容易写的方法来处理它,即:

IEnumerable<T> GetRow(T[,] array, int row) 
{ 
    for (int i = 0; i <= array.GetUpperBound(1); ++i) 
     yield return array[row, i]; 
} 

IEnumerable<T> GetColumn(T[,] array, int column) 
{ 
    for (int i = 0; i <= array.GetUpperBound(0); ++i) 
     yield return array[i, column]; 
} 

那么你可以做:

var row1Sum = GetRow(d_array, 1).Sum(); 
0

了IEnumerable语法也不太工作为了我。它在GetRow和GetColumn后缺少“Angle Bracket-T-Angle支架”。以下语法运行良好。谢谢!

public static IEnumerable<T> GetRow<T>(T[,] array, int row) 
    { 
     for (int i = 0; i <= array.GetUpperBound(1); ++i) 
      yield return array[row, i]; 
    } 
    public static IEnumerable<T> GetColumn<T>(T[,] array, int column) 
    { 
     for (int i = 0; i <= array.GetUpperBound(0); ++i) 
      yield return array[i, column]; 
    }