필터 지우기
필터 지우기

Distance between points in a table

조회 수: 3 (최근 30일)
KK14
KK14 2020년 11월 15일
답변: Adam Danz 2020년 11월 19일
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
Adam Danz
Adam Danz 2020년 11월 16일
or pdist2
KK14
KK14 2020년 11월 19일
Hello,
I do not have access to the tool box. But anyways thanks for letting me know about 'pdist'.
BR

댓글을 달려면 로그인하십시오.

답변 (1개)

Adam Danz
Adam Danz 2020년 11월 19일
>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,:).

Community Treasure Hunt

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

Start Hunting!

Translated by