How to calculate Euclidian distance between two points defined by matrix containing x, y?

maycca picture maycca · Jul 15, 2014 · Viewed 46.3k times · Source

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.

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, so point A: [x1,y1] point B: [x2,y2]

Points coordinations:

Points position

A[0,1]
B[0,0] 
C[1,1]
D[1,1]

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)

so I obtain

> 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)

To calculate euclidean distance between

A <-> B  # same as x1[1,] <-> x2[1,]
C <-> D  # same as x1[2,] <-> x2[2,]

I assume to obtain 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

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

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.

Answer

Shambho picture Shambho · Jul 15, 2014

If you just want a vector, something like this will work for you.

Try something like this:

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,])

This will work for any dimensions.

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

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.