Euclidean Distance (Back to the Math...complete with two loops)
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Joe Bannen
am 20 Mär. 2016
Bearbeitet: Joe Bannen
am 21 Mär. 2016
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 Kommentare
Akzeptierte Antwort
Roger Stafford
am 20 Mär. 2016
Bearbeitet: Roger Stafford
am 20 Mär. 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 Kommentare
Roger Stafford
am 20 Mär. 2016
Bearbeitet: Roger Stafford
am 20 Mär. 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.
Weitere Antworten (1)
Chad Greene
am 20 Mär. 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));
1 Kommentar
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!