这里有点新鲜!我试图计算2个向量之间的Mahalanobis距离,我需要计算2个向量之间的协方差矩阵。 我有以下代码来执行此操作:基本上,向量是大小为1x8的行向量。这些向量存储在变量x1和x2中。然后取这些2的差异并存储在差异中。 有一个单独的函数来计算协方差矩阵,它存储在covar1中。 但是,当我执行此操作时,我在计算协方差矩阵的逆的行上得到运行时错误1004:
covarinv = WorksheetFunction.MInverse(covar1)
对此的任何帮助都将非常感激! 谢谢。
Sub calculat()
Dim x1() As Variant
Dim x2() As Variant
Dim diff() As Variant
Dim covar1 As Variant
Dim covarinv As Variant
Dim md() As Variant
x1 = Range("b3:i3")
x2 = Range("b4:i4")
n1 = UBound(x1, 1)
n2 = UBound(x1, 2)
m1 = UBound(x2, 1)
m2 = UBound(x2, 2)
ReDim diff(1 To n1, 1 To n2)
For j = 1 To n1
For i = 1 To n2
diff(j, i) = x1(j, i) - x2(j, i)
Next i
Next j
covar1 = VarCov(Range("b3:i7"))
covarinv = WorksheetFunction.MInverse(covar1)
temp = WorksheetFunction.MMult(diff, covarinv)
difft = WorksheetFunction.Transpose(diff)
md = WorksheetFunction.MMult(temp, difft)
End Sub
Function VarCov(rng As Range) As Variant
Dim i As Integer
Dim j As Integer
Dim colnum As Integer
Dim matrix() As Double
colnum = rng.Columns.Count
ReDim matrix(colnum - 1, colnum - 1)
For i = 1 To colnum
For j = 1 To colnum
matrix(i - 1, j - 1) = Application.WorksheetFunction.covar(rng.Columns(i), rng.Columns(j))
Next j
Next i
VarCov = matrix
End Function