【发布时间】:2012-12-07 08:13:42
【问题描述】:
我有 2 个列表,其中包含点的 X、Y 坐标。 列表 1 包含的点比列表 2 多。
任务是以最小化整体欧式距离的方式找到点对。
我有一个工作代码,但我不知道这是否是最好的方法,我想知道我可以改进的结果(找到最小值的更好算法)或速度,因为列表是关于每个 2000 个元素。
样本向量中的轮次也用于获得具有相同距离的点。 使用“rdist”功能,所有距离都以“距离”生成。比矩阵中的最小值用于链接 2 点(“dist_min”)。这两个点的所有距离现在都被替换为 NA 并且循环继续搜索下一个最小值,直到列表 2 的所有点都具有列表 1 中的点。 最后,我添加了一个可视化图。
require(fields)
set.seed(1)
x1y1.data <- matrix(round(runif(200*2),2), ncol = 2) # generate 1st set of points
x2y2.data <- matrix(round(runif(100*2),2), ncol = 2) # generate 2nd set of points
distances <- rdist(x1y1.data, x2y2.data)
dist_min <- matrix(data=NA,nrow=ncol(distances),ncol=7) # prepare resulting vector with 7 columns
for(i in 1:ncol(distances))
{
inds <- which(distances == min(distances,na.rm = TRUE), arr.ind=TRUE)
dist_min[i,1] <- inds[1,1] # row of point(use 1st element of inds if points have same distance)
dist_min[i,2] <- inds[1,2] # column of point (use 1st element of inds if points have same distance)
dist_min[i,3] <- distances[inds[1,1],inds[1,2]] # distance of point
dist_min[i,4] <- x1y1.data[inds[1,1],1] # X1 ccordinate of 1st point
dist_min[i,5] <- x1y1.data[inds[1,1],2] # Y1 coordinate of 1st point
dist_min[i,6] <- x2y2.data[inds[1,2],1] # X2 coordinate of 2nd point
dist_min[i,7] <- x2y2.data[inds[1,2],2] # Y2 coordinate of 2nd point
distances[inds[1,1],] <- NA # remove row (fill with NA), where minimum was found
distances[,inds[1,2]] <- NA # remove column (fill with NA), where minimum was found
}
# plot 1st set of points
# print mean distance as measure for optimization
plot(x1y1.data,col="blue",main="mean of min_distances",sub=mean(dist_min[,3],na.rm=TRUE))
points(x2y2.data,col="red") # plot 2nd set of points
segments(dist_min[,4],dist_min[,5],dist_min[,6],dist_min[,7]) # connect pairwise according found minimal distance
【问题讨论】:
-
寻找暗物质 kaggle 竞赛问题,也许?
-
伪代码很容易写:
for (i in 1st.set.points) { for (j in j 2nd.set.points){calculate: sqrt((x1st.set.ponint-x2nd.set.points)^2+(y1st.set.ponint-y2nd.set.points)^2), save every resulting value then call min() function to determine which has the lowest value } } -
嗨 java_xof,我想这就是我所做的。?
distances <- rdist(x1y1.data, x2y2.data)提供所有距离的矩阵,which(distances == min(distances,na.rm = TRUE), arr.ind=TRUE)在矩阵中搜索分钟。但万一有一对具有相同的最小值。距离我不知道该选哪对。