MATLAB Answers

Distance between points in a table

4 views (last 30 days)
KK14
KK14 on 15 Nov 2020
Answered: Adam Danz on 19 Nov 2020
Hello all,
I have a table containing the (x,y) coordinates and I need to find the distance between each point and save it as an array. Could anybody please guide me?
Thanks in advance.

  3 Comments

Geoff Hayes
Geoff Hayes on 16 Nov 2020
K1495 - what can you tell us about your table? Can you convert it to an mx2 array for each of your m points? If you have the Statistics and Machine Learning Toolbox, you could probably use pdist.
KK14
KK14 on 19 Nov 2020
Hello,
I do not have access to the tool box. But anyways thanks for letting me know about 'pdist'.
BR

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 19 Nov 2020
>I have a table containing the (x,y) coordinates and I need to find the distance between each point [without using pdist | pdist2]
Calculate distances row-wise
Create input table
rng('default')
T = array2table(rand(8,2).*10, 'VariableNames',{'X','Y'})
T = 8x2 table
X Y ______ ______ 8.1472 9.5751 9.0579 9.6489 1.2699 1.5761 9.1338 9.7059 6.3236 9.5717 0.9754 4.8538 2.785 8.0028 5.4688 1.4189
Add a column Dist that shows the distance between rows n and n-1.
T.Dist = [NaN; sqrt(diff(T.X).^2 + diff(T.Y).^2)]
T = 8x3 table
X Y Dist ______ ______ _______ 8.1472 9.5751 NaN 9.0579 9.6489 0.91367 1.2699 1.5761 11.217 9.1338 9.7059 11.311 6.3236 9.5717 2.8134 0.9754 4.8538 7.1317 2.785 8.0028 3.632 5.4688 1.4189 7.1099
Calculate pairwise distances
Create input table
rng('default')
T = array2table(rand(8,2).*10, 'VariableNames',{'X','Y'})
T = 8x2 table
X Y ______ ______ 8.1472 9.5751 9.0579 9.6489 1.2699 1.5761 9.1338 9.7059 6.3236 9.5717 0.9754 4.8538 2.785 8.0028 5.4688 1.4189
Create square matrix of pairwise distances
[xi, yi] = meshgrid(1:numel(T.X), 1:numel(T.Y));
D = reshape(sqrt(diff(T.X([xi(:),yi(:)]),1,2).^2 + diff(T.Y([xi(:),yi(:)]),1,2).^2),size(xi))
D = 8×8
0 0.9137 10.5490 0.9952 1.8236 8.5864 5.5880 8.5847 0.9137 0 11.2171 0.0949 2.7354 9.3979 6.4853 8.9786 10.5490 11.2171 0 11.3108 9.4588 3.2908 6.6029 4.2019 0.9952 0.0949 11.3108 0 2.8134 9.4922 6.5732 9.0613 1.8236 2.7354 9.4588 2.8134 0 7.1317 3.8708 8.1975 8.5864 9.3979 3.2908 9.4922 7.1317 0 3.6320 5.6559 5.5880 6.4853 6.6029 6.5732 3.8708 3.6320 0 7.1099 8.5847 8.9786 4.2019 9.0613 8.1975 5.6559 7.1099 0
D(i,j) is the distance between points T(i,:) and T(j,:).

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by