Smooth high-frequency data array with moving averages

Recently I had to implement a way to smooth high-frequency data from the phone's accelerometer. The refresh rate was 16ms, so there is a lot of noise, to simply fix it, I decided to go with moving averages.

To implement a moving averages technique in Swift, you could use the following approach:

  1. Define a function that takes in your array of doubles and the window size for the moving average as parameters.
  2. Initialize an empty array to store the smoothed values.
  3. Iterate through the array of doubles and calculate the average of the current value and the previous windowSize - 1 values. This will be the smoothed value for the current index.
  4. Append the smoothed value to the array of smoothed values.
  5. Return the array of smoothed values.

Here's some example code that demonstrates this approach:

func smooth(data: [Double], windowSize: Int) -> [Double] {
    var smoothedValues: [Double] = []
    for i in 0..<data.count {
        let start = max(0, i - windowSize + 1)
        let end = i
        let window = data[start...end]
        let average = window.reduce(0, +) / Double(window.count)
        smoothedValues.append(average)
    }
    return smoothedValues
}

This function will take in an array of doubles and a window size, and it will return an array of the same size where each value is the average of the current value and the previous windowSize - 1 values. For example, if you call smooth(data: [1, 2, 3, 4, 5], windowSize: 3), it will return [2, 3, 4, 5], because the smoothed value for each index is the average of the current value and the two previous values.