MATLAB: Distance between all points of two vectors

distanceeuclidean

Hello,
'x' and 'y' are two vectors having respectively x and y coordinates of spatial locations.
x = [1;3;1;4;5]
y = [5;4;3;1;1]
I am trying to calculate distance between all the pairs (point 1 to 2, 2 to 3 etc, total 10). Here is what i did:
for i = 1:length(x)-1
for j = i+1:length(x)
D = (sqrt((x(i) - x(j)).^2 + (y(i) - y(j)).^2))
end
end
The distance D for all pairs are calculated correctly. How can i modify this code so that all the distances are saved in D as a vector.
Thanks
Bineet

Best Answer

Loops are rarely needed in matlab. They just make the code more complicated. Case in point:
D = hypot(x-x.', y-y.');
All done!
If you just want the upper triangular matrix of the above as a vector:
Dvec = D(triu(true(size(D)), 1));