How can I determine the distance of two points, if the point's coord are in other vectors?
Ältere Kommentare anzeigen
Dear All,
Please help me!
I have got 5 random points (just for example). Each of them has an X coordinate and a Y coordinate. These coords are in two vectors:
example (becasue every element of the vectors are randomly generated) X=[1,5,8,8,2]; Y=[5,6,8,4,2]; P1(1,5); P2(5,6) and so on P5(2,2);
so I would like to determine each of the distances between each points. I mean d_1_2=sqrt((x1-x2)^2+(y1-y2)^2) . . .
d_1_5=sqrt((x1-x5)^2+(y1-y5)^2)
I would like to use the distances in the future, so I need all of them.
Thank you!
Szabi
Akzeptierte Antwort
Weitere Antworten (1)
X = [1,5,8,8,2];
Y = [5,6,8,4,2];
Dist = sqrt(bsxfun(@plus, X.^2, Y(:).^2);
This does not have a loop and does not consider, that the resulting matrix is symmetric, such that a loop could have the double speed in theory:
X = [1,5,8,8,2];
Y = [5,6,8,4,2];
Dist = zeros(length(X), length(Y));
for iY = 1:length(Y)
YY = Y(iY)^2; % Avoid repeated calculation
Dist(iY, iY) = sqrt(X(iY)^2 + YY); % Diagonal element
for iX = iY + 1:length(X)
d = sqrt(X(iX)^2 + YY);
Dist(iX, iY) = d;
Dist(iY, iX) = d; % Mirroring
end
end
But if you are not talking about billions of points, squaring the values once is more efficient:
XX = X .* X;
YY = Y .* Y;
Dist = zeros(length(X), length(Y));
for iY = 1:length(Y)
Dist(iY, iY) = sqrt(X(iY)^2 + YY(iY)); % Diagonal element
for iX = iY + 1:length(X)
d = sqrt(XX(iX) + YY(iY));
Dist(iX, iY) = d;
Dist(iY, iX) = d; % Mirroring
end
end
Kategorien
Mehr zu Mathematics and Optimization finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!