0

我正在尝试计算 VBA 中的马氏距离。

我创建了我的 UDF 来计算协方差矩阵,但是在执行我的函数时出现#value 错误。

你能给我一些帮助吗

提前致谢!

Function DMahalanobis(x As Range, y As Range) As Variant
    Dim c() As Variant, k As Variant, U As Range, a() As Variant, b() As Variant
    Set U = Application.Union(x, y)
    Debug.Print U
    k = x.Columns.Count
    a = x
    b = y
    ReDim c(1, k)
    For i = 1 To k Step 1
        c(1, i) = a(1, i) - b(1, i)
    Next i
    DMahalanobis = Application.MMult(Application.MMult(Application.Transpose(c), Application.MInverse(MVARCOVAR(U))), c)
End Function

这是我的 VarCovar 函数,可以正常工作

'Function to calculate Covariance matrix
Function MVARCOVAR(RANGO As Range) As Variant
Dim c() As Variant, i As Long, k As Long, j As Long
k = RANGO.Columns.Count
Debug.Print k
ReDim c(k, k)
 For i = 1 To k Step 1
  For j = 1 To k Step 1
  c(i, j) = Application.Covar(Application.Index(RANGO, , i), Application.Index(RANGO, , j))
  Next j
 Next i
MVARCOVAR = c
End Function

在此处输入图像描述

4

1 回答 1

1

可能是由于该行中的单一问题:

DMahalanobis = Application.MMult(Application.MMult(Application.Transpose(c), Application.MInverse(MVARCOVAR(U))), c).

根据你给定的输入,维数Uis 2xk, as 2<<k,U 的协方差矩阵可能包含一些缺失值,当你取逆时,它会弹出一个错误。或许可以尝试换成U整个数据集,否则在计算马氏距离时无法捕捉到数据中的分布信息。

于 2020-04-16T14:23:50.107 回答