看来我不是唯一一个与此斗争的人,但我找不到一个好的答案,所以我在这里试试这个机会!
我想找到一个最佳拟合的三次多项式线,给出两组存储在数组中的数据。基本上,它看起来像那样
Dim X(0 to 9) as Integer
Dim Y(0 to 9) as Integer
for k = 0 to 9
X(k) = 'something
Y(k) = 'something else
Next
到目前为止,我已经找到了如何使用1次多项式Y = aX + b来解决我的问题:
a = Application.WorksheetFunction.LinEst(Y, X, True, False)(1)
b = Application.WorksheetFunction.LinEst(Y, X, True, False)(2)
我还发现,如果将值X和Y写入工作表,我可以找到更高的多项式:
'x-axis values are entered in X column, y-values in Y column
Z = Application.Evaluate("=linest(Y1:Y10,X1:X10^{1,2,3})")
'The answer is in Z such that Y = Z(1)*Y^3+Z(2)*Y^2+Z(3)*Y+Z(4)
假设我的数组已经排序,我如何将linest
与数组一起使用而不是在单元格中输入值?
答案 0 :(得分:1)
如果你想要OLS最佳拟合系数(即线性回归)而不是插值,那么对于二阶多项式你可以这样做:
Sub test()
Dim X(0 To 9, 0 To 1) As Integer
Dim Y(0 To 9, 0 To 0) As Integer
i = 0
For n = 0 To 9
X(n, 0) = i
X(n, 1) = i * i
Y(n, 0) = i * i + 3 * i - 7
i = i + 1
Next
B = WorksheetFunction.LinEst(Y, X)
B2 = B(1)
B1 = B(2)
B0 = B(3)
End Sub
这正确地返回-7
的{{1}},B0
的{{1}}和3
的{{1}}。这与答案几乎相同:https://stackoverflow.com/a/27137957/1011724
你可以使它更通用,比如说B1
- 这样的多项式:
1
答案 1 :(得分:1)
我找到了另一种使用数组进行多项式回归的方法。代码在此链接中。 https://rosettacode.org/wiki/Polynomial_regression。由于网站中的代码由于数组不正确而无法运行,我做了一个小更正。现在可以使用了。
Function polynomial_regression(y As Variant, x As Variant, degree As Integer) As Variant
Dim a() As Double
ReDim a(1 To UBound(x), 1 To degree)
For i = 1 To UBound(x)
For j = 1 To degree
a(i, j) = x(i) ^ j
Next j
Next i
polynomial_regression = WorksheetFunction.LinEst(WorksheetFunction.Transpose(y), a, True, True)
End Function