Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate Euclidean distance between two matrices in R

Tags:

r

I have two huge matrices with equal dimensions. I want to calculate Euclidean distance between them. I know this is the function:

euclidean_distance <- function(p,q){
  sqrt(sum((p - q)^2))
}

and if these are two matrices:


set.seed(123)
    mat1 <- data.frame(x=sample(1:10000,3), 
                       y=sample(1:10000,3), 
                       z=sample(1:10000,3))
    mat2 <- data.frame(x=sample(1:100,3), 
                       y=sample(1:100,3), 
                       z=sample(1:1000,3))

then I need the answer be a new matrix 3*3 showing Euclidean distance between each pair of values of mat1 and mat2.

any suggestion please?

like image 802
zara Avatar asked Jan 30 '16 20:01

zara


People also ask

How do you calculate Euclidean distance in R?

Euclidean distance is the shortest possible distance between two points. 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.

How do you find the distance of a matrix in R?

The dist() function in R can be used to calculate a distance matrix, which displays the distances between the rows of a matrix or data frame. where: x: The name of the matrix or data frame.

How do you find the distance between two matrices?

If we have two matrices A,B. Distance between A and B can be calculated using Singular values or 2 norms. You may use Distance =|(fnorm(A)−fnorm(B))| where fnorm = sq root of sum of squares of all singular values.

How do you find the Euclidean distance between two arrays?

In this method, we first initialize two numpy arrays. Then, we take the difference of the two arrays, compute the dot product of the result, and transpose of the result. Then we take the square root of the answer. This is another way to implement Euclidean distance.


1 Answers

This is a job for the base function outer:

outer(mat1,mat2,Vectorize(euclidean_distance))
         x         y         z
x  9220.40  9260.736  8866.034
y 12806.35 12820.086 12121.927
z 11630.86 11665.869 11155.823
like image 176
A. Webb Avatar answered Oct 18 '22 20:10

A. Webb