# We need library emuR for the eplot() function

library(emuR)

# Function from 08_formantprocessing for
# calculating Euclidean distance 
euc = function(a, b) {
  sqrt(sum((a - b)^2))
}
# read in 2 columned data
fdat = read.table("formantidata.df.txt")

# plot 95% confidence ellipse of that data
eplot(fdat)
# supermipose a point on the ellipse
vec = c(-0.9649036, 0.5113503)
text(vec[1], vec[2],  "X", col = 2, cex=2)

# calculate the centroid of data (mean of each column)
centroid = apply(fdat, 2, mean)
# Euclidean distance of vec to the centroid
euc(vec, centroid)
# Mahalanobis distance requires calculating the covariance matrix
covmat = var(fdat)
# Mahalanobis distance of vec to the centroid
mahalanobis(vec, centroid, covmat)

# given that the point is on the 95% confidence ellipse, 
# the above should be close to:
qchisq(.95, 2)
# which it is. 

# Just by the way: The second argument, 2 in the above function, is because the data is 2-dimensional. You may remember that a 95% confidence interval for a one-dimensional normal distribution corresponds to ±1.96 standard deviations i.e
sqrt(qchisq(.95, 1))

# Another by the way. An ellipse is a horizontal slice through a two dimensional normal distribution. If the two dimensions are uncorrelated, then the ellipse turns into a circle (and there is no covariance).
