Euclidean Distance (Back to the Math...complete with two loops)
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi
Sorry to ask this as it appears to have been asked loads before! I am trying to construct a code with two loops to calculate the Euclidean Distance between elements of two matrices. I have code which uses repmat and avoids loops but now I need to show an element by element calculation.
I seem to be able to do this on a per element basis but I can't figure out how to 'automate' the loops. They need to be left in so that the Mathematics is much clearer.
% Loop Test Script
A=[2 3 4;1 6 5;4 3 1];
B=[5 1 2;3 2 6;8 0 7];
C=zeros(3);
for l=1:3 % rows
for m=1:3 % columns
C(l,m)=sum(A(l,m)-B(l,m)).^2; % Not working!!
end
end
C
Here, element C(2,1) would be (1-5).^2 + (6-1).^2 + (5-2).^2. This is simple to implement in more advanced code.
Any help with keeping the loops and implementing this properly would be most welcome.
Sincerely
Joe
댓글 수: 0
채택된 답변
Roger Stafford
2016년 3월 20일
편집: Roger Stafford
2016년 3월 20일
Apparently what you want is this:
for l = 1:3
for m = 1:3
C(l,m) = sum((A(l,:)-B(m,:)).^2);
end
end
This would be squared euclidean distance. To get euclidean distance you need to take the square root of the 'C' values. Note that this is what the function 'pdist2' would give you.
댓글 수: 5
Roger Stafford
2016년 3월 20일
편집: Roger Stafford
2016년 3월 20일
The code I gave you gives the result you want:
C =
17 6 54
50 21 89
6 27 61
However, if you want Euclidean distance, you must take the square root of each of these values.
추가 답변 (1개)
Chad Greene
2016년 3월 20일
The euclidean distance is a strange term to apply to this particular problem. For each row,column pair you have a value in A and a value in B. For such a one-dimensional problem the euclidean distance is simply
C = abs(A-B)
You're taking the square of a sum of a difference in your calculation. That changes the units, whatever your units are, they become squared the way you're calculating C. Do your A and B matrices represent differences in separate dimensions? If so, perhaps this is what you want:
C = hypot(A,B)
which, if for some reason you need to calculate in a loop, could be done in a loop by
C(l,m) = hypot(A(l,m),B(l,m));
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!