问题描述
欧几里得距离计算让我很失落.我发现函数dist2 {SpatialTools}或rdist {fields}可以做到这一点,但是它们不能按预期工作.
I am very lost in Euclidean distance calculation. I have found functions dist2{SpatialTools} or rdist{fields} to do this, but they doesn´t work as expected.
我想一个点在笛卡尔系统中有两个坐标,所以[x,y].要测量2点之间的距离(按行定义),我需要2点的4个坐标,所以点A:[x1,y1]B点:[x2,y2]
I suppose that one point has two coordinates in carthesian system, so [x,y].To measure distance between 2 points (defined by row), I need 4 coordinates for 2 points, sopoint A: [x1,y1]point B: [x2,y2]
要点协调:
A[0,1]
B[0,0]
C[1,1]
D[1,1]
我有两个矩阵: x1 (A和C在那,由行定义)和 x2 (包含B和D).写入矩阵:
I have two matrices: x1(A and C are there, defined by rows) and x2 (contain B and D). Written in matrix:
library("SpatialTools")
x1<-matrix(c(0,1,1,1), nrow = 2, ncol=2, byrow=TRUE)
x2<-matrix(c(0,0,1,1), nrow = 2, ncol=2, byrow=TRUE)
所以我得到
> x1
[,1] [,2]
[1,] 0 1 #(as xy coordinates of A point)
[2,] 1 1 #(same for C point)
> x2
[,1] [,2]
[1,] 0 0 #(same for B point)
[2,] 1 1 #(same for D point)
计算之间的欧式距离
A <-> B # same as x1[1,] <-> x2[1,]
C <-> D # same as x1[2,] <-> x2[2,]
我假设要获取 EuclidDist :
> x1 x2 EuclidDist
[,1] [,2] [,1] [,2]
[1,] 0 1 #A [1,] 0 0 #B 1
[2,] 1 1 #B [2,] 1 1 #D 0
我只想获取由[x,y]坐标标识的两点之间的距离的矢量 ,但是,使用dist2
我可以获得一个矩阵:
I would like just to obtain vector of distances between two points identified by [x,y] coordinates, however, using dist2
I obtain a matrix:
> dist2(x1,x2)
[,1] [,2]
[1,] 1.000000 1
[2,] 1.414214 0
我的问题是,根据该矩阵,哪些数字描述了A-B和C-D之间的实际欧几里得距离?我误会了吗?非常感谢您的任何建议或任何解释.
My question is, which numbers describe the real Euclidean distance between A-B and C-D from this matrix? Am I misunderstanding something? Thank you very much for every advice or any explanation.
推荐答案
如果您只想使用矢量,类似的方法将对您有用.
If you just want a vector, something like this will work for you.
尝试这样的事情:
euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
library(foreach)
foreach(i = 1:nrow(x1), .combine = c ) %do% euc.dist(x1[i,],x2[i,])
这将适用于任何尺寸.
如果不想使用foreach,可以使用一个简单的循环:
If you don't want to use foreach, you can use a simple loop:
dist <- NULL
for(i in 1:nrow(x1)) dist[i] <- euc.dist(x1[i,],x2[i,])
dist
尽管如此,我还是建议foreach(因为对于像这样的各种任务来说非常容易).在软件包的文档中详细了解它.
Although, I would recommend foreach (because it's very easy to for various tasks like this). Read more about it in the documentation of the package.
这篇关于如何计算由包含x,y的矩阵定义的两点之间的欧几里得距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!