I am hoping to make this method run a little faster. I typically need to run this on a list with more than 100000 entries. Note that at the start and end of the list, I wish to weight the average so that it is closer to the start or end value, hence the smaller framesize.
public PointPairList GetMovingAverage(int frameSize, PointPairList data)
{
PointPairList movAvgPoints = new PointPairList();
//Smooth each point in the list
for (int i = 0; i < data.Count; i++)
{
//get the window range
int actualFrameSize = frameSize;
int start = i - (frameSize/2);
int end = i + (frameSize/2);
//ensure the window is the same size at the source list boundaries
if (start < 0)
{
actualFrameSize = frameSize + start;
start = 0;
}
if (end >= data.Count)
{
actualFrameSize = frameSize + (data.Count - 1 - end);
}
//Now get the sum of the window
double sum = data.Skip(start).Take(actualFrameSize).Sum(p => p.Y);
//add the average point to the result
movAvgPoints.Add(new PointPair(data[i].X, sum/actualFrameSize));
}
return movAvgPoints;
}
PointPairList
constructor overload can take acapacity
parameter, you can pre-allocate the size of the list, such likeList<T>
does and score a little performance gain by constructing it withdata.Count
. \$\endgroup\$