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
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.

更多回答(1 个)

Sriram Tadavarty
Sriram Tadavarty 2020-3-17
编辑:Sriram Tadavarty 2020-3-17
Hi Marco,
You can use the pdist and pdist2 functions in the Statistics Toolbox
XY = [ 0 0; 1 0; 2 0; 3 0; 0 -1;1 -1;2 -1;3 -1];
disp(XY)
pdist(XY) % THis will provide all the distances with all the combinations
Hope this helps.
Regards,
Sriram

类别

Help CenterFile 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!

Translated by