Circular moving average filter in LINQ
.net, c#, filtering, linq, signal-processing
Solution
Expanding on my comment, you could use the mod (`%`) operator to get `k` to wrap from `0` to `ylength - 1`
// 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++)
{
sum += y[(k + yLength) % yLength];
}
yfiltered[i] = sum / (2 * halfWindowWidth + 1);
}
Problem
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); } ```