Euclidean Distance

Fox picture Fox · Mar 14, 2013 · Viewed 11.5k times · Source

I have two points

 x1 = (a1,b1,c1,d1,e1);    //5 dimensional point
 x2 = (a2,b2,c2,d2,e2);    //5 dimensional point

So is this right way to calculate the euclidean dist?

  d = sqrt(sqr(a1-a2)+sqr(b1-b2)+sqr(c1-c2)+sqr(d1-d2)+sqr(e1-e2))

Now I was wondering if the pdist(X) would give me the same result?

Here X = (x1,x2) i.e X is a 5x2 matrix.

Also I would like the result in square matrix form.

Answer

Pursuit picture Pursuit · Mar 14, 2013

There are a lot of answers to this. In general, yes, you have the right math, although not the correct Matlab syntax.

Given some X as you describe:

X = [1 3 4 2 1; 8 2 3 5 4]

Here is the syntax for the equation you were writing out:

d1 = sqrt((X(1,1)-X(2,1))^2+(X(1,2)-X(2,2))^2+(X(1,3)-X(2,3))^2+(X(1,4)-X(2,4))^2+(X(1,5)-X(2,5))^2)

Here are a couple of more idiomatic ways to format this equation:

d2 = sqrt(sum(  (X(1,:) - X(2,:)).^2  ))
d3 = sqrt(sum(       diff(X,[],1).^2))

Here is a more functional way to compute it

euclidDistance = @(x,y)  sqrt(sum( (x-y).^2));
d4 = euclidDistance(X(1,:), X(2,:))

Note, all of these methods return the same result: d1=d2=d3=d4 = 8.3066