Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Euclidean distance of two vectors

Tags:

r

How do I find the Euclidean distance of two vectors:

x1 <- rnorm(30) x2 <- rnorm(30) 
like image 408
Jana Avatar asked Apr 05 '11 22:04

Jana


People also ask

How do you find the Euclidean distance between two vectors in R?

Formula to calculate this distance is : Euclidean distance = √Σ(xi-yi)^2 where, x and y are the input values. The distance between 2 arrays can also be calculated in R, the array function takes a vector and array dimension as inputs.

What is the formula for Euclidean distance between two points?

Euclidean Distance Examples Determine the Euclidean distance between two points (a, b) and (-a, -b). d = 2√(a2+b2). Hence, the distance between two points (a, b) and (-a, -b) is 2√(a2+b2).

What is the Euclidean distance between these two objects?

In mathematics, the Euclidean distance between two points in Euclidean space is the length of a line segment between the two points. It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, therefore occasionally being called the Pythagorean distance.


2 Answers

Use the dist() function, but you need to form a matrix from the two inputs for the first argument to dist():

dist(rbind(x1, x2)) 

For the input in the OP's question we get:

> dist(rbind(x1, x2))         x1 x2 7.94821 

a single value that is the Euclidean distance between x1 and x2.

like image 172
Gavin Simpson Avatar answered Sep 28 '22 04:09

Gavin Simpson


As defined on Wikipedia, this should do it.

euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2)) 

There's also the rdist function in the fields package that may be useful. See here.


EDIT: Changed ** operator to ^. Thanks, Gavin.

like image 35
Erik Shilts Avatar answered Sep 28 '22 05:09

Erik Shilts