Euclidean Distance (Back to the Math...complete with two loops)
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Roger Stafford
on 20 Mar 2016
Edited: Roger Stafford
on 20 Mar 2016
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 Comments
Roger Stafford
on 20 Mar 2016
Edited: Roger Stafford
on 20 Mar 2016
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.
More Answers (1)
Chad Greene
on 20 Mar 2016
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));
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!