Reputation: 25
I have a list of arrays and I'm trying to average over the columns of a group of always four of these arrays.
As an example:
UInt16[] array_0 = new UInt16[]{ 1, 2, 3, 4};
UInt16[] array_1 = new UInt16[]{ 7, 2, 3, 4};
// ...
var lists = new UInt16[120][];
lists[0] = array_0;
lists[1] = array_1;
// ...
The result should be a list of arrays. Each array is filled with the averages of each first, second,.. element over four arrays. The first result_array should contain the average from thr first element of the first four groups (array 0-3), the second element of this group and so on. The second result_array should contain the average from thr first element of the second four groups (array 4-7), the second element of this group and so on.
UInt16[] array_0 = {1 2 3 4}
UInt16[] array_1 = {1 2 3 4}
UInt16[] array_2 = {3 4 5 6}
UInt16[] array_3 = {3 4 5 6}
UInt16[] ergebnis1= {2 3 4 5}
UInt16[] array_4 = {2 1 3 4}
UInt16[] array_5 = {4 1 3 4}
UInt16[] array_6 = {3 2 3 4}
UInt16[] array_7 = {3 4 3 4}
UInt16[] ergebnis2= {4 2 3 4} // Mean of the first four elements, second four elements,..
What I can only do by now is to average over every column of the whole list like this:
var listLengths = lists.Select(x => x.Count());
var lengthOfEachList = listLengths.First();
var averages = new List<double>();
for (var i = 0; i != lengthOfEachList; i = i+1)
{
averages.Add(lists.Average(x => x[i]));
}
Does anyone has an idea how to solve it?
Upvotes: 0
Views: 162
Reputation: 449
Here is a function to compute the average for a group of arrays.
double[] AverageSets(int numberOfArrays, int offset, int[,] array)
{
var length = array.GetLength(1);
var avgs = new double[length];
double n = 1;
for (int i = offset; i < offset + numberOfArrays; i++)
{
for (var j = 0; j < length; j++)
{
avgs[j] = avgs[j] * (n-1) / n + array[i,j] / n;
}
n++;
}
return avgs;
}
Here is an example were the average is computed for arrays 1-3.
int[,] array =
{
{1, 2, 3, 4},
{1, 2, 3, 4},
{3, 4, 5, 6},
{3, 4, 5, 6},
{2, 1, 3, 4},
{4, 1, 3, 4},
{3, 2, 3, 4},
{3, 4, 3, 4}
};
var results = AverageSets(3, 1, array);
results = [ 2.33333333333333, 3.33333333333333, 4.33333333333333, 5.33333333333333 ]
This should give you the utility you need to loop over the larger array you have in mind. (This code assumes you chopped the array of arrays into equal parts, additional error handling will be needed if the last block of arrays is shorter than the number of arrays you want to average together).
for(int i = 0;i < lists.Count;i += numberOfArraysYouWantAveraged)
{
AverageSets(numberOfArraysYouWantAveraged, i, lists);
}
Upvotes: 0
Reputation: 71
var averageslow = new List<double>();
var averageshigh = new List<double>();
for (var i = 0; i < 4; i++)
{
averageslow.Add(lists.Average(x => x[i]));
}
for (var i = 4; i < 8; i++)
{
averageshigh.Add(lists.Average(x => x[i]));
}
Upvotes: 0