我必须将方差-协方差矩阵中的值缩小到方差(矩阵中的对角线值(通过收缩因子(lambda(,因此:λ*收缩矩阵+(1-λ(*方差协方差矩阵,其中:
方差协方差矩阵为:
Function VarCovar(rng As Range) As Variant
Dim i As Integer
Dim j As Integer
Dim numcols As Integer
numcols = rng.Columns.Count
numrows = rng.Rows.Count
Dim matrix() As Double
ReDim matrix(numcols - 1, numcols - 1)
For i = 1 To numcols
For j = 1 To numcols
matrix(i - 1, j - 1) = Application.WorksheetFunction.Covar(rng.Columns(i), rng.Columns(j)) * numrows / (numrows - 1)
Next j
Next i
VarCovar = matrix
,这给了我一个矩阵,如下所示:
0.40 -0.10 0.11
-0.10 0.17 -0.03
0.11 -0.03 0.19
然后我在创建收缩矩阵时遇到问题,它应该看起来像:
0.40 0.00 0.00
0.00 0.17 0.00
0.00 0.00 0.19
即仅返回对角线值(= 变量的方差(和所有其他单元格中的零。
因此,以某种方式,使其返回一个矩阵,该矩阵仅包含行=列号的值,即(1,1(、(2,2( 和 (3,3( 值。
有人可以帮助解决这个问题吗?
你只需要一个循环,从i = 1 to 3
开始计数,以填充Matrix(1, 1)
,Matrix(2, 2)
并使用Matrix(3, 3)
Matrix(i, i)
Function VarCovar(InputMatix As Range) As Variant
Dim MatrixColumns As Long
MatrixColumns = InputMatix.Columns.Count
Dim MatrixRows As Long
MatrixRows = InputMatix.Rows.Count
Dim Matrix() As Double
ReDim Matrix(1 To MatrixColumns, 1 To MatrixColumns)
Dim i As Long
For i = 1 To MatrixColumns
Matrix(i, i) = Application.WorksheetFunction.Covar(InputMatix.Columns(i), InputMatix.Columns(i)) * MatrixRows / (MatrixRows - 1)
Next i
VarCovar = Matrix
End Function
请注意,我将Matrix
dienstions Matrix(1 To MatrixDimension, 1 To MatrixDimension)
更改为以 1
开头而不是以 0
开头,因此您可以轻松地使用它将其写入单元格:
Sub test()
Range("A5:C7").Value = VarCovar(Range("A1:C3"))
End Sub