How to calculate the euclidean distance in matlab?

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

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 CenterFile Exchange 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by