Function moransI(xRng As Range, wRng As Range) As Double
' x must be column of length n
' w must be n-by-x matrix
Dim x As Variant, w As Variant
Dim n As Long, i As Long, j As Long
Dim sumW As Double, xBar As Double, xVar As Double, ss As Double
x = xRng
w = wRng
n = UBound(x, 1)
sumW = WorksheetFunction.Sum(w)
xBar = WorksheetFunction.Average(x)
xVar = WorksheetFunction.VarP(x)
For i = 1 To n: For j = 1 To n
ss = ss + w(i, j) * (x(i, 1) - xBar) * (x(j, 1) - xBar)
Next j, i
' simplification:
' note that VARP(x) = SUMPRODUCT((x(i,1)-xBar)^2)/n
' so:
' n*ss / (2*sumW*SUMPRODUCT((x(i,1)-xBar)^2))
' = n*ss / (2*sumW*n*xVar)
' which equals:
moransI = ss / (sumW * xVar)
End Function
Function gearysC(xRng As Range, wRng As Range) As Double
' x must be column of length n
' w must be n-by-x matrix
Dim x As Variant, w As Variant
Dim n As Long, i As Long, j As Long
Dim sumW As Double, xBar As Double, xVar As Double, ss As Double
x = xRng
w = wRng
n = UBound(x, 1)
sumW = WorksheetFunction.Sum(w)
xBar = WorksheetFunction.Average(x)
xVar = WorksheetFunction.Var(x)
For i = 1 To n: For j = 1 To n
ss = ss + w(i, j) * (x(i, 1) - x(j, 1)) ^ 2
Next j, i
' simplification:
' note that VAR(x) = SUMPRODUCT((x(i,1)-xBar)^2)/(n-1)
' so:
' (n-1)*ss / (2*sumW*SUMPRODUCT((x(i,1)-xBar)^2))
' = (n-1)*ss / (2*sumW*(n-1)*xVar)
' which equals:
gearysC = ss / (2 * sumW * xVar)
End Function