How can I determine the distance of two points, if the point's coord are in other vectors?

1 view (last 30 days)
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

Accepted Answer

Sean de Wolski
Sean de Wolski on 12 Aug 2013
If you have the Statistics Toolbox
doc pdist
Else:
doc hypot
  2 Comments
szasza654 szasza654
szasza654 szasza654 on 27 Aug 2013
sorry for the late
so, i am very glad for your answer, but it is the hard way, and i now these commands. i would like to solve the problem with some kind of loop or don' t know.. in my case there are a lot of points (many many), and i would like to know each distance point pairs..(putting a new point if the new point's distance is bigger than 8 mm from every other (previously packed point-- i tried to make for loops, but didn' t work all right). if you have another tip, please wright it! thx :)
Jan
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.

Sign in to comment.

More Answers (1)

Jan
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

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!