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.
Quan Wang (2020). Pair-wise Euclidean Distance Matrix (https://www.mathworks.com/matlabcentral/fileexchange/45968-pair-wise-euclidean-distance-matrix), MATLAB Central File Exchange. Retrieved .
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.
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);
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!