Calculating all distances between one point and a group of points efficiently in R

后端 未结 5 615
太阳男子
太阳男子 2020-12-15 09:55

First of all, I am new to R (I started yesterday).

I have two groups of points, data and centers, the first one of size n and

5条回答
  •  再見小時候
    2020-12-15 10:48

    Rather than iterating across data points, you can just condense that to a matrix operation, meaning you only have to iterate across K.

    # Generate some fake data.
    n <- 3823
    K <- 10
    d <- 64
    x <- matrix(rnorm(n * d), ncol = n)
    centers <- matrix(rnorm(K * d), ncol = K)
    
    system.time(
      dists <- apply(centers, 2, function(center) {
        colSums((x - center)^2)
    })
    )
    

    Runs in:

    utilisateur     système      écoulé 
          0.100       0.008       0.108 
    

    on my laptop.

提交回复
热议问题