How to calculate the euclidean distance in matlab?

12 ビュー (過去 30 日間)
Avinash Bhatt
Avinash Bhatt 2019 年 5 月 26 日
編集済み: KALYAN ACHARJYA 2019 年 5 月 26 日
I have coordinates as
pix_cor=[2 1;2 2; 2 3]
I want to calculate the eucledian distance between
1) (2,1) and (2,1);
2) (2,1) and (2 2);
3) (2,1) and (2,3);
Simarlarily
4) (2,2) and (2,1);
5) (2,2) and (2 2);
6) (2,2) and (2,3);
and
7) (2,3) and (2,1);
8) (2,3) and (2 2);
9) (2,3) and (2,3);
The formulae is (x2-x1)^2+(y2-Y1)^2
The result will be h=[0 1 1;1 0 1;4 1 0]
Please help me achieving this in matlab

採用された回答

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 5 月 26 日
編集済み: KALYAN ACHARJYA 2019 年 5 月 26 日
%#Edited
x=[2,1];
y=[2,1];
D=sqrt((y(1)-x(1))^2+(y(2)-x(2))^2);
Result:
D =
0
So on.......% do the same for others
  1 件のコメント
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 5 月 26 日
編集済み: KALYAN ACHARJYA 2019 年 5 月 26 日
Yes my bad, please read the answer by @John you are right.

サインインしてコメントする。

その他の回答 (1 件)

John D'Errico
John D'Errico 2019 年 5 月 26 日
Actually, that is simply NOT the formula for Euclidean distance. You need to take the square root to get the distance. So, you showed the formula for the square of the distance.
pix_cor=[2 1;2 2; 2 3];
x = pix_cor(:,1);
y = pix_cor(:,2);
Now, what does MATLAB do if you form differences like these?
x - x'
and
y - y'
TRY IT! Learn to use MATLAB!
So the trick is to square those matrices, then add the results, then take the square root. Like this:
dist_E = sqrt((x - x').^2 + (y - y').^2)
dist_E =
0 1 2
1 0 1
2 1 0
As I said, the Euclidean distance NEEDS a square root though. It you don't believe me, then do some reading here:
The above line of code does require MATLAB release R2016b. With an older release, you would use bsxfun.
dist_E = sqrt(bsxfun(@minus,x,x').^2 + bsxfun(@minus,y,y').^2);

カテゴリ

Help Center および File ExchangeStatistics and Machine Learning Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by