Question

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.

Was it helpful?

Solution

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

OTHER TIPS

yes. it is the right way.

For MATLAB use pdist2(x1,x2,'euclidean')

Since the Euclidean distance between two vectors is the two-norm of their difference, you can use:

d = norm( x1 - x2, 2 ) 

to calculate it. If the second argument is missing, 2-norm is assumed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top