Calculating Euclidean distance of pairs of 3D points.

29 views (last 30 days)
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 for this without loop ?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 11 Sep 2014
Edited: Andrei Bobrov on 11 Sep 2014
use Statistics Toolbox:
out = squareform(pdist(Nm)); % here Nm - your matrix [Nx3]
one variant without Statistics Toolbox:
nc = num2cell(Nm,2);
[x,y] = ndgrid(1:N);
out = cellfun(@(x,y)sqrt(sum((x-y).^2)),nc(x),nc(y));
other variant
out = squeeze(sqrt(sum(bsxfun(@minus,Nm,permute(Nm,[3,2,1])).^2,2)));
  1 Comment
Josh Wiley
Josh Wiley on 15 Oct 2015
regarding the last variant, when I use this with a 2x3 matrix, the output is a 2x2 matrix with the distance appearing twice, what might be the cause of that?

Sign in to comment.

More Answers (1)

Roger Stafford
Roger Stafford on 11 Sep 2014
Use matlab's 'pdist' and 'squareform' functions

Categories

Find more on Statistics and Machine Learning Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!