Distance between one point and the next of a list of points?
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi guys,
I have a list of points like this one:
XY = [0 0;
1 0;
2 0;
3 0;
0 -1;
1 -1;
2 -1;
3 -1];
disp(XY);
I would like to find a function that calculates the Cartesian distance between each point and its consecutive of this list.
Anyone can help me?
Thank you so much!
채택된 답변
Image Analyst
2020년 3월 17일
Try this:
XY = [0 0;
1 0;
2 0;
3 0;
0 -1;
1 -1;
2 -1;
3 -1]
consecutiveDistances = sqrt((x(2:end) - x(1:end-1)) .^ 2 + (y(2:end) - y(1:end-1)) .^ 2)
You'll see
consecutiveDistances =
1
1
1
3.1623
1
1
1
Another nice function you might want to know about, if you have the Statistics and Machine Learning Toolbox, is pdist2(). You can use pdist2(XY, XY) tol give distances between every point and every point in a 2-D array:
XY = [0 0;
1 0;
2 0;
3 0;
0 -1;
1 -1;
2 -1;
3 -1]
distances = pdist2(XY, XY)
You'll see:
distances =
0 1 2 3 1 1.4142 2.2361 3.1623
1 0 1 2 1.4142 1 1.4142 2.2361
2 1 0 1 2.2361 1.4142 1 1.4142
3 2 1 0 3.1623 2.2361 1.4142 1
1 1.4142 2.2361 3.1623 0 1 2 3
1.4142 1 1.4142 2.2361 1 0 1 2
2.2361 1.4142 1 1.4142 2 1 0 1
3.1623 2.2361 1.4142 1 3 2 1 0
The columns and row numbers refer to the row in your XY list. So for example, the element at Row 2, Column 3 of distances corresponds to the distance between point (row) 2 of your XY, and point (row) 3 of your XY. So you'd want to look at the diagonal one above the main upper left-to-lower right diagonal. You'll see it is the same list of numbers as consecutiveDistances.
댓글 수: 0
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!