Distance between all points of two vectors

9 Ansichten (letzte 30 Tage)
Bineet_Mehra
Bineet_Mehra am 2 Mär. 2020
Kommentiert: Bineet_Mehra am 2 Mär. 2020
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

Akzeptierte Antwort

Guillaume
Guillaume am 2 Mär. 2020
Bearbeitet: Guillaume am 2 Mär. 2020
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 Kommentare
Guillaume
Guillaume am 2 Mär. 2020
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.
Bineet_Mehra
Bineet_Mehra am 2 Mär. 2020
thanks Guillaume !!!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by