How to divide a distance into some equal parts?
79 views (last 30 days)
Mohammad Sami on 25 Jan 2020
Assuming the coordinates are variable p1, p2
% p1 = [x1 y1];
% p2 = [x2 y2];
midpoint = p1 + 0.5.* (p2-p1); % halfway point
% just change 0.5 to something else for other point along the line between p1 and p2
John D'Errico on 25 Jan 2020
Edited: John D'Errico on 25 Jan 2020
You have two points. Call they xy1 and xy2, where the xy are row vectors of length 2. For example...
xy1 = [-1,3];
xy2 = [2,5];
Now, you wish to create new points, that are equally spaced in distance along the line that connects the points. Lets say you want to divide the line segment into n equal parts. That means, including the two original points, you will have n+1 points as a result, with n-1 additional points created. I'll pick, for example, n=5 here. So there will be 5 segments of equal length, so 4 new points to be created in addition.
n = 5;
t = linspace(0,1,n+1)';
xy = (1-t)*xy1 + t*xy2;
As you can see, xy is an array with n+1 rows and 2 columns. The first and last rows are the original points, with the desired 4 new rows in between.
If you want to appreciate why it works so simply, note that I have taken a weighted linear combination of xy1 and xy2. Some would call this a convex linear combination, I suppose. The important thing to understand is that the weights, thus (1-t) and t respectively, sum to 1, and they are created using a tool like linspace, so they uniformly vary from 0 to 1.