問題描述
如何從多維數組中取出一些值,然后計算平均選擇值?
How do I sort out some values from multidimensional Array and then calculate the average selected value?
所以當我點擊某個圖像時,它不僅應該在鼠標指針所在的點顯示深度數據(來自 Microsoft Kinect),而且還應該計算環境中的值(即多維數組).
So when I click some Image, it should show depth data (from Microsoft Kinect) not only in the point where the mouse pointer stands, but also it should calculate the value in the environment (which is multidimensional Array).
這是我的代碼:
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] 中的所有值求和?是否可以計算每一行的總和(->一維數組/向量),然后再次計算列的總和(->零維數組/標量)?
So, firstly: how do I sum all the values from d_array[m,n] ? Is it possible to calculate the sum of each row (-> one dimensional Array / vector) and then calculate again the sum of the column (-> zero-dimensional Array / scalar)?
推薦答案
所以,首先:如何對 d_array[m,n] 中的所有值求和
So, firstly: how do I sum all the values from d_array[m,n]
你可以使用:
int sum = d_array.Cast<int>().Sum();
這將自動展平多維數組并取所有元素的總和.
This will automatically flatten out the multidimensional array and take the sum of all elements.
是否可以先計算每一行的總和(->一維數組/向量),然后再計算列的總和(->零維數組/標量)?
Is it possible to calculate the sum of each row (-> one dimensional Array / vector) and then calculate again the sum of the column (-> zero-dimensional Array / scalar)?
是的,但這需要手動循環.沒有一個簡單的方法可以解決這個問題,盡管編寫方法來處理它很容易,即:
Yes, but this would require looping manually. There is no simple one liner for this, though it would be easy to write methods to handle it, ie:
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();
這篇關于Sum 多維數組 C#的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!