Mojtaba
Mojtaba

Reputation: 33

Calculating Euclidean distance of pairs of 3D points in matlab

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 ?

Upvotes: 3

Views: 3217

Answers (3)

Payam Ahmadvand
Payam Ahmadvand

Reputation: 151

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);

Upvotes: 1

zinjaai
zinjaai

Reputation: 2385

To complete the comment of Divakar:

x = rand(10,3);
pdist2(x, x, 'euclidean')   

Upvotes: 0

Shai
Shai

Reputation: 114796

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 ) );

Upvotes: 1

Related Questions