How to calculate the euclidean distance in matlab?
조회 수: 27 (최근 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
댓글 수: 0
채택된 답변
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
2019년 5월 26일
편집: KALYAN ACHARJYA
2019년 5월 26일
Yes my bad, please read the answer by @John you are right.
추가 답변 (1개)
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);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!