3

I have an Nx3 array that contains N 3D points

a1 b1 c1 
a2 b2 c2
.... 
aN bN cN 

I want to calculate Euclidean distance in a NxN array that measures the Euclidean distance between each pair of 3D points. (i,j) in result array returns the distance between (ai,bi,ci) and (aj,bj,cj). Is it possible to write a code in matlab without loop ?

Shai
  • 111,146
  • 38
  • 238
  • 371
Mojtaba
  • 33
  • 1
  • 4

3 Answers3

1

Use pdist and squareform:

D = squareform( pdist(X, 'euclidean' ) ); 

For beginners, it can be a nice exercise to compute the distance matrix D using (hover to see the solution).

elemDiff = bsxfun( @minus, permute(X,[ 1 3 2 ]), permute(X, [ 3 1 2 ]) );
D = sqrt( sum( elemDiff.^2, 3 ) );

Shai
  • 111,146
  • 38
  • 238
  • 371
1

The challenge of your problem is to make a N*N matrix and the result should return in this matrix without using loops. I overcome this challenge by giving suitable dimension to Bsxfun function. By default X and ReshapedX should have the same dimensions when we call bsxfun function. But if the size of the matrixes are not equal and one of them has a singleton (equal to 1) dimension, the matrix is virtually replicated along that dimension to match the other matrix. Therefore, it returns N*3*N matrix which provides subtraction of each 3D point from the others.

ReshapedX = permute(X,[3,2,1]);
DiffX = bsxfun(@minus,X,ReshapedX);
DistX =sqrt(sum(DiffX.^2,2));
D = squeeze(DistX);
0

To complete the comment of Divakar:

x = rand(10,3);
pdist2(x, x, 'euclidean')   
Shai
  • 111,146
  • 38
  • 238
  • 371
zinjaai
  • 2,345
  • 1
  • 17
  • 29
  • `pdist2` needs approx twice the number of distance computation compared to `pdist` in this case. – Shai Sep 11 '14 at 07:42