user2754279 - 1 year ago 117
C# Question

# Sum multidimensional array C#

How do I sort out some values from multidimensional Array and then calculate the average selected value?

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).

This is my code:

``````    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;
}
}
}
``````

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)?

So, firstly: how do I sum all the values from d_array[m,n]

You can use:

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

You could then do:

``````var row1Sum = GetRow(d_array, 1).Sum();
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download