How can I determine the distance of two points, if the point's coord are in other vectors?
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Sean de Wolski
on 12 Aug 2013
If you have the Statistics Toolbox
doc pdist
Else:
doc hypot
2 Comments
Jan
on 27 Aug 2013
Edited: Jan
on 27 Aug 2013
Accepting an answer means, that it solves the problem.
"Many many" could mean 64 or 64'000'000'000. Such details matter, so please be as explicit as possible.
If you have some code, post it here and explain "didn't work all right" with more details. Then it is easy to suggest an improvement.
More Answers (1)
Jan
on 27 Aug 2013
Edited: Jan
on 27 Aug 2013
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
0 Comments
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!