Distance between all points of two vectors

17 次查看(过去 30 天)
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.

请先登录,再进行评论。

更多回答(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