這裏是一個gnuplot的唯一樣本數據的解決方案:
set table "test.data"
set samples 1000
plot rand(0)+sin(x)
unset table
您應該檢查gnuplot demo頁面正在運行的平均值。我將通過動態構建函數來概括這個演示。這使得改變平均點包含的點數變得更容易。
這是腳本:
# number of points in moving average
n = 50
# initialize the variables
do for [i=1:n] {
eval(sprintf("back%d=0", i))
}
# build shift function (back_n = back_n-1, ..., back1=x)
shift = "("
do for [i=n:2:-1] {
shift = sprintf("%sback%d = back%d, ", shift, i, i-1)
}
shift = shift."back1 = x)"
# uncomment the next line for a check
# print shift
# build sum function (back1 + ... + backn)
sum = "(back1"
do for [i=2:n] {
sum = sprintf("%s+back%d", sum, i)
}
sum = sum.")"
# uncomment the next line for a check
# print sum
# define the functions like in the gnuplot demo
# use macro expansion for turning the strings into real functions
samples(x) = $0 > (n-1) ? n : ($0+1)
avg_n(x) = (shift_n(x), @sum/samples($0))
shift_n(x) = @shift
# the final plot command looks quite simple
set terminal pngcairo
set output "moving_average.png"
plot "test.data" using 1:2 w l notitle, \
"test.data" using 1:(avg_n($2)) w l lc rgb "red" lw 3 title "avg\\_".n
這是結果:
平均滯後相當多的身後,從算法預期的數據點。也許50分太多了。或者,可以考慮實施一個居中移動平均線,但這超出了這個問題的範圍。 而且,我也認爲你用外部程序更靈活:)
我已經更新了我的問題,好心的看看 – saif