I’m looking for an elegant way to implement a moving average filter in c#. Now, that would be easy, but at the borders, the averaging window shall wrap around the start/end. This kind of made my code ugly and unintuitive, and I was wondering whether there was a smarter way to solve this using LINQ or so.
So what I currently have is:
// input is a List<double> y, output is List<double> yfiltered
int yLength = y.Count;
for (int i = 0; i < yLength; i++)
{
double sum = 0.0;
for (int k = i - halfWindowWidth; k <= i + halfWindowWidth; k++)
{
if (k < 0)
{
// k is negative, wrap around
sum += y[yLength - 1 + k];
}
else if (k >= yLength)
{
// k exceeds y length, wrap around
sum += y[k - yLength];
}
else
{
// k within y.Count
sum += y[k];
}
}
yfiltered[i] = sum / (2 * halfWindowWidth + 1);
}
Expanding on my comment, you could use the mod (
%) operator to getkto wrapfrom
0toylength - 1