Distance between all points of two vectors

조회 수: 17 (최근 30일)
Bineet_Mehra
Bineet_Mehra 2020년 3월 2일
댓글: Bineet_Mehra 2020년 3월 2일
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

채택된 답변

Guillaume
Guillaume 2020년 3월 2일
편집: Guillaume 2020년 3월 2일
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
Guillaume
Guillaume 2020년 3월 2일
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 2020년 3월 2일
thanks Guillaume !!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by