Skip to content
Prev 269514 / 398502 Next

Efficient way to Calculate the squared distances for a set ofvectors to a fixed vector

You could do something like this:

# data
nrows <- 20000L
ncols <- 5L
myVec <- array(rnorm(nrows * ncols), dim = c(nrows, ncols))
y <- rnorm(ncols)

temp <- t(myVec) - y
result <- colSums(temp * temp)

# check
all.equal(as.numeric(crossprod(myVec[1L, ] - y)), result[1L])
#...

(And don't use a data.frame, but a matrix.)

regards,
Enrico