Julia Signal Smoothing
Signal smoothing is the process of softening sharp jumps in a list of numbers. The method used here is called moving average.
A window of three smooths five numbers to three
Each output is the mean of three neighbors in a row. The list 2.0, 4.0, 6.0, 8.0, and 10.0 gives three outputs.
data = [2.0, 4.0, 6.0, 8.0, 10.0]
println([(data[i] + data[i + 1] + data[i + 2]) / 3 for i in 1:3])A window of two gives three outputs from four numbers
Each output is the mean of two neighbors in a row. The list 1.0, 3.0, 5.0, and 7.0 gives three outputs.
data = [1.0, 3.0, 5.0, 7.0]
println([(data[i] + data[i + 1]) / 2 for i in 1:3])A reusable function smooths any list
The function takes a list and a window size. It returns one mean for each full window.
function moving_average(data, window)
return [(sum(data[i:i + window - 1]) / window) for i in 1:(length(data) - window + 1)]
end
println(moving_average([10.0, 12.0, 11.0, 13.0, 12.0], 3))Example
function moving_average(data, window)
return [(sum(data[i:i + window - 1]) / window) for i in 1:(length(data) - window + 1)]
end
data = [10.0, 12.0, 11.0, 13.0, 12.0]
println(data)
println(moving_average(data, 3))Key points
- Window: a window is a small group of neighbors averaged together.
- Moving average: a moving average replaces each window with its mean value.
- Window size: a window of three averages three numbers at a time.
- Edges: the output list is shorter than the input list, because full windows are needed.
- Sharp jumps: smoothing softens sharp jumps while keeping the overall shape.
In this example, a function averages each window of three numbers in the input list. The first line prints the input list. The second line prints the smoothed list, which is shorter than the input list.
Note
every output here is an exact value, with no rounding step.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What is the moving average of 2.0, 4.0, and 6.0 in one window?