Distance between all points of two vectors

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

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

6 Comments

Thanks Guillaume,
there is an error while computing Dvec
Array indices must be positive integers or logical values.
thanks
Do'h! Fixed (replace ones by true)
thanks works well !!
Though the problem is solved, i wonder what changes we can make to the for loop above to get the same result. Just out of curosity !!!
The easiest would have been to build a 2D matrix (as my first line of code does) and then extract the relevant part as a vector. For building the 2D matrix, you just need to add indexing into D:
D(i, j) = sqrt((x(i) - x(j)).^2 + (y(i) - y(j)).^2); %better written as hypot(x(i)-x(j), y(i)-y(j))
But it would be much better to preallocate the matrix before the loop:
D = zeros(numel(x)); %preallocation to avoid growing the matrix in the loop (which is slow)
for i = 1:numel(x)-1
for j = i+1:numel(x)
D(i, j) = hypot(x(i)-x(j), y(i)-y(j));
end
end
Dvec = D(triu(true(size(D)), 1));
If you want to build a vector from scratch:
Dvec = zeros(1, sum(1:numel(x)-1));
didx = 1;
for i = 1:numel(x)-1
for j = i+1:numel(x)
Dvec(idx) = hypot(x(i)-x(j), y(i)-y(j));
idx = idx + 1;
end
end
But overall:
D = hypot(x-x.', y-y.');
Dvec = D(triu(true(size(D)), 1));
is much simpler.
thanks Guillaume !!!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!