【问题标题】:Find closest value for every row in a matrix from another matrix从另一个矩阵中找到矩阵中每一行的最接近值
【发布时间】:2016-11-18 02:54:52
【问题描述】:

我已经生成了 5 个坐标(每个坐标由一个 x 和一个 y 变量组成,它们被认为是“真相”。

D <- 2 #amount of dimensions
K <- 5
events <- 2*K #number of events
truth <- matrix(data=runif(events, min = 0, max = 1), nrow=K)

然后我生成了另一组坐标,在本例中为两个:

E <- 2    
test <- matrix(data=runif(2*E, min = 0, max = 1), nrow=E)

现在我想知道这前五个坐标中的哪一个最接近(在欧几里得意义上)这两个测试坐标中的每一个。最简单的方法是什么?

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用fields 包中的rdist 来计算test 中的每一行与truth 中的每一行之间的欧几里得距离矩阵。首先是数据:

    set.seed(123)  ## for reproducibility
    D <- 2 #amount of dimensions
    K <- 5
    events <- 2*K #number of events
    truth <- matrix(data=runif(events, min = 0, max = 1), nrow=K)
    ##          [,1]      [,2]
    ##[1,] 0.2875775 0.0455565
    ##[2,] 0.7883051 0.5281055
    ##[3,] 0.4089769 0.8924190
    ##[4,] 0.8830174 0.5514350
    ##[5,] 0.9404673 0.4566147
    
    E <- 2    
    test <- matrix(data=runif(2*E, min = 0, max = 1), nrow=E)
    ##          [,1]      [,2]
    ##[1,] 0.9568333 0.6775706
    ##[2,] 0.4533342 0.5726334
    

    使用rdist计算距离矩阵:

    library(fields)
    d <- rdist(test,truth)
    ##          [,1]      [,2]      [,3]      [,4]      [,5]
    ##[1,] 0.9205136 0.2252589 0.5884781 0.1461471 0.2215612
    ##[2,] 0.5525263 0.3379176 0.3228474 0.4302058 0.5007584
    

    要找到最接近每个test 行的truth 行,apply which.minMARGIN=1 的行重叠:

    apply(d,1,which.min)
    ##[1] 4 3
    

    【讨论】:

      【解决方案2】:

      如果您想避免必须计算每个行组合的距离,避免使用基数 dist,并且不使用任何外部包,您可以通过先制作两个符合矩阵来手动编码欧几里得距离。

      diffs   <- truth[rep(1:nrow(truth), nrow(test)),] -test[rep(1:nrow(test), each=nrow(truth)),]
      eucdiff <- function(x) sqrt(rowSums(x^2))
      max.col(-matrix(eucdiff(diffs), nrow=nrow(test), byrow=TRUE), "first")
      #[1] 4 3
      

      使用上面@aichao的数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-25
        • 2022-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-13
        相关资源
        最近更新 更多