フィルターのクリア

Distance between all points of two vectors

22 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by