VBA中的马哈拉诺比斯距离

时间:2017-01-09 04:32:55

标签: vba statistics mahalanobis

我正在尝试计算VBA中的马哈拉诺比斯距离。

我已经创建了我的UDF来计算Covarince矩阵,但在执行我的函数时出现了#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

enter image description here

1 个答案:

答案 0 :(得分:1)

可能是由于该行中存在单个问题:

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

根据给定的输入,U的维数为2xk,因为2<<k的U的协方差矩阵可能包含一些缺失值,当您取逆时,它将弹出出现错误。也许您可以尝试将U更改为整个数据集,否则在计算马哈拉诺比斯距离时您将无法捕获数据中的分布信息。