Code covered by the BSD License  

Highlights from
Pair-wise Euclidean Distance Matrix

3.0 | 1 rating Rate this file 18 Downloads (last 30 days) File Size: 2.62 KB File ID: #45968 Version: 1.2
image thumbnail

Pair-wise Euclidean Distance Matrix


Quan Wang (view profile)


21 Mar 2014 (Updated )

Computing the distance matrix without loops

| Watch this File

File Information

This is a very simple function to compute pair-wise Euclidean distances within a vector set, from between two vector sets. Although simple, it is very useful. Using loops will be too slow.
D=distanceMatrix(X), where X is N*d data, and D is N*N distance matrix.

or D=distanceMatrix2(X,Y).

Required Products MATLAB
MATLAB release MATLAB 8.2 (R2013b)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (1)
21 May 2014 Jonas Lundgren

Jonas Lundgren (view profile)

Dear Quan Wang,

It is a widespread misunderstanding that MATLAB loops are slow in general. Loops with simple math operations can be very fast. Waste of memory is always slow and so is the function repmat.

Compare distanceMatrix(X) with distmat(X) below. X = rand(1000,3).

I am sure you will reply with something even faster. I look forward to update the rating.

Kind regards
Jonas Lundgren

function D = distmat(X)
%DISTMAT Compute euclidian distance matrix from coordinates

[n,dim] = size(X);
D = zeros(n);
for j = 1:n
for k = 1:dim
v = X(:,k) - X(j,k);
D(:,j) = D(:,j) + v.*v;
D = sqrt(D);

20 May 2014 1.1

Added distance matrix from X to Y.

20 May 2014 1.2

Changed the description.

Contact us