0

I am attempting to replicate a function for WLS (Weighted Least Squares) that I have found in a textbook in excel. There is a value error coming up and I think that I am doing something wrong in using the function.

The following is the VBA code for a supporting function Diag(w) and the function itself WLSregress():

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

This function should return the WLS estimator for the explanatory variables of equation being estimated. I understand the code leading up to the k = Application.Count(b) line but not too sure how the output bit is working.

If anyone could help me figure out why this isn't working I would be very grateful.

The following is an example image of the function trying to work. example

4

1 に答える 1

3

デフォルトでは、特に指定しない限り、Excel は配列のサイズを 0 から開始します。例えば、

Redim arr(2,2)

実際には3 x 3の配列が得られます

      0       1       2
0    blank | blank | blank
1    blank | blank | blank
2    blank | blank | blank

このため、 がある場合ReDim temp(n, n)、実際には、実際に必要な行と列よりも 1 つ多くの行と列を持つ配列を作成しています。あなたの例では、A3:18 のダイアログが 16 x 16 のダイアログであると予想されますが、実際には 17 x 17 のダイアログが作成され、行列の乗算が破棄されます (つまりApplication.MMult) 。

この行を置き換えます

ReDim temp(n, n)

この行で

ReDim temp(1 to n, 1 to n)

これで、結果が返されるはずです。結果が正確であるかどうかを判断するのはあなた次第です。

于 2013-11-07T05:09:12.617 に答える