library(magrittr)
data(iris)
set.seed(1)
data <- iris[sample(nrow(iris)), ] # 打散資料
Xtrain <- data[1:100, 1:4]
Xtest <- data[101:150, 1:4]
M <- nrow(Xtrain)
N <- nrow(Xtest)

# 雙層迴圈
distmatrix <- matrix(0, nrow = M, ncol = N)
for (i in 1:M) {
  for (j in 1:N) {
    distmatrix[i, j] <- 
      sum((Xtrain[i,] - Xtest[j,]) ^ 2) %>% 
      sqrt
  }
} # 約五秒

# 改成展開所有配對的二個大矩陣；不用迴圈
res <-
  (Xtrain[rep(1:M, N),] - Xtest[rep(1:N, each = M),]) ^ 2 %>%
  rowSums %>%
  sqrt %>%
  matrix(M, N)
# 馬上算好不用等

identical(distmatrix, res) # 二種結果相同
# your code goes here