Savitzky-Golayフィルタ関数を定義します。この関数では、入力データの配列、窓幅、多項式次数、微分の次数を引数として取ります。
Function SavitzkyGolayFilter(data As Variant, window As Integer, order As Integer, deriv As Integer) As Variant
Dim i As Integer, j As Integer, k As Integer
Dim sum As Double, a As Double, b As Double
Dim coef() As Double
Dim filteredData() As Double
Dim n As Integer
n = UBound(data)
ReDim filteredData(n)
ReDim coef(order + 1, window)
For i = 0 To n
sum = 0
For j = -window To window
If (i + j >= 0 And i + j <= n) Then
For k = 0 To order
coef(k, j + window) = coef(k, j + window) + (j ^ k)
Next k
sum = sum + data(i + j)
End If
Next j
filteredData(i) = sum
Next i
For i = 0 To order
For j = 0 To window
coef(i, j) = coef(i, j) / coef(0, window)
Next j
Next i
For i = 0 To n
a = 0
For j = -window To window
If (i + j >= 0 And i + j <= n) Then
a = a + coef(deriv, j + window) * data(i + j)
End If
Next j
filteredData(i) = a
Next i
SavitzkyGolayFilter = filteredData
End Function
実際にフィルタリングを行うには、以下のように関数を呼び出します
Sub ApplySavitzkyGolayFilter()
Dim inputData() As Double
inputData = Range("A1:A100").Value
Dim window As Integer
window = 5
Dim order As Integer
order = 2
Dim deriv As Integer
deriv = 0
Dim outputData() As Double
outputData = SavitzkyGolayFilter(inputData, window, order, deriv)
Range("B1:B100").Value = outputData
End Sub