Skip to content

Instantly share code, notes, and snippets.

@AndrewLJackson
Last active May 23, 2019 06:07
Show Gist options
  • Save AndrewLJackson/f5d91db9b1c5c20cd4e2 to your computer and use it in GitHub Desktop.
Save AndrewLJackson/f5d91db9b1c5c20cd4e2 to your computer and use it in GitHub Desktop.
# code based on https://en.wikipedia.org/wiki/Mahalanobis_distance
set.seed(1)
# define a point D
x <- matrix(rmnorm(1, c(2,2), matrix(c(1,0.1,0.1,1), 2, 2)), 1, 2) # vector of locations in 2 dimensional space
x <- t(x) # transpose
# Define a multivariate normal distribution for comparison
mu <- matrix(c(0, 0), 1, 2) # vector of bivariate means
mu <- t(mu) # transpose
S <- matrix(c(1,0,0,1), 2, 2) # covariance matrix
# calculate D(x)
D <- sqrt( t(x - mu) %*% solve(S) %*% (x - mu) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment