fork download
  1. library(magrittr)
  2. data(iris)
  3. set.seed(1)
  4. data <- iris[sample(nrow(iris)), ] # 打散資料
  5. Xtrain <- data[1:100, 1:4]
  6. Xtest <- data[101:150, 1:4]
  7. M <- nrow(Xtrain)
  8. N <- nrow(Xtest)
  9.  
  10. # 雙層迴圈
  11. distmatrix <- matrix(0, nrow = M, ncol = N)
  12. for (i in 1:M) {
  13. for (j in 1:N) {
  14. distmatrix[i, j] <-
  15. sum((Xtrain[i,] - Xtest[j,]) ^ 2) %>%
  16. }
  17. } # 約五秒
  18.  
  19. # 改成展開所有配對的二個大矩陣;不用迴圈
  20. res <-
  21. (Xtrain[rep(1:M, N),] - Xtest[rep(1:N, each = M),]) ^ 2 %>%
  22. rowSums %>%
  23. sqrt %>%
  24. matrix(M, N)
  25. # 馬上算好不用等
  26.  
  27. identical(distmatrix, res) # 二種結果相同
  28. # your code goes here
Success #stdin #stdout 3.8s 48700KB
stdin
Standard input is empty
stdout
[1] TRUE