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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With