Effacer les filtres
Effacer les filtres

How to calculate the euclidean distance in matlab?

27 vues (au cours des 30 derniers jours)
Avinash Bhatt
Avinash Bhatt le 26 Mai 2019
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

Réponse acceptée

KALYAN ACHARJYA
KALYAN ACHARJYA le 26 Mai 2019
Modifié(e) : KALYAN ACHARJYA le 26 Mai 2019
%#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 commentaire
KALYAN ACHARJYA
KALYAN ACHARJYA le 26 Mai 2019
Modifié(e) : KALYAN ACHARJYA le 26 Mai 2019
Yes my bad, please read the answer by @John you are right.

Connectez-vous pour commenter.

Plus de réponses (1)

John D'Errico
John D'Errico le 26 Mai 2019
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);

Catégories

En savoir plus sur Operators and Elementary Operations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by