我正在尝试复制我在 Excel 教科书中找到的 WLS(加权最小二乘)函数。出现值错误,我认为我在使用该函数时做错了。
以下是支持函数 Diag(w) 和函数本身 WLSregress() 的 VBA 代码:
Function Diag(W) As Variant
Dim n, i, j, k As Integer
Dim temp As Variant
n = W.Count
ReDim temp(n, n)
For i = 1 To n
For j = 1 To n
If j = i Then temp(i, j) = W(i) Else temp(i, j) = 0
Next j
Next i
Diag = temp
End Function
Function WLSregress(y As Variant, X As Variant, W As Variant) As Variant
Wmat = Diag(W)
n = W.Count
Dim Xtrans, Xw, XwX, XwXinv, Xwy As Variant
Dim m1, m2, m3, m4 As Variant
Dim output() As Variant
Xtrans = Application.Tranpose(X)
Xw = Application.MMult(Xtrans, Wmat)
XwX = Application.MMult(Xw, X)
XwXinv = Application.MInverse(XwX)
Xwy = Application.MMult(Xw, y)
b = Application.MMult(XwXinv, Xwy)
k = Application.Count(b)
ReDim output(k) As Variant
For bcnt = 1 To k
output(bcnt) = b(bcnt, 1)
Next bcnt
WLSregress = Application.Transpose(output)
End Function
此函数应返回被估计方程的解释变量的 WLS 估计器。我了解导致该k = Application.Count(b)
行的代码,但不太确定输出位是如何工作的。
如果有人可以帮助我弄清楚为什么这不起作用,我将不胜感激。
以下是该功能尝试工作的示例图像。