[英]How to calculate the max euclidean distance between two elements in a matrix - R?
我有一个 0 和 1 的 100x100 矩阵。 我正在尝试计算矩阵中任意 2 个 1 整数之间的最大欧几里得距离。
我应该找到彼此相距最远的两个integer中的position并使用它们吗?
提前谢谢了
最简单的方法是对所有可能的点进行蛮力搜索。 这是可行的,因为矩阵的大小是可控的:
set.seed(123)
m <- matrix(sample(c(1,0), size = 100^2, replace = TRUE), 100, 100)
max_dist <- 0
coord <- numeric()
for (i in 1:100){
for (j in 1:100){
for (k in 1:100){
for (l in 1:100){
if (m[i,j] == 1 && m[k,l] == 1){
dist <- sqrt((i-k)^2+(j-l)^2)
if (dist > max_dist){
max_dist <- dist
coord <- c(i,j,k,l)
}
}
}
}
}
}
在这里,如果遇到一对距离大于前一个最大值并且它们都等于1的点,我们会更新最大距离和点的坐标。在这个例子中,最大距离等于138.6,坐标为(1 ,1) 和 (98,100)。
这是一种避免通过 for 循环查看矩阵的每个元素的方法。
# set up
set.seed(123)
n <- 100
m <- matrix(sample(c(1,0), size = n^2, replace = TRUE), n, n)
# find the ones in the matrix and calculates the distances
ind <- which(m==1, arr.ind=TRUE)
dists <- dist(ind) # default euclidean
# look for the largest entry, and convert it to index position
ind1d <- which.max(dists)
ind2d <- arrayInd(ind1d, .dim=rep(nrow(ind),2))
# get answer
ans <- ind[as.vector(ind2d),]
ans
# row col
#[1,] 98 100
#[2,] 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.