Plot a line between 2 points and extend the line a determined distance
77 views (last 30 days)
Show older comments
I am plotting a line between points: p1 and p2. Finally I want to extend this line a determined distance so it will still pass through p1 and p2 and it will be longer.
Image 1 shows the plotted line which correctly passes through p1 and p2
But when I try to extend this line I get a longer line but with a bad angle as it does not pass through p2:
Here is all the code (fillline.m is a function that can be found in File Exchange):
% Points
pto1 = [3.4353 0.2521];
pto2 = [39.5904 -20.6633];
% Original line
[line_x,line_y]=fillline(pto1(1,:), pto2(1,:),100);
line_xy = [line_x' line_y'];
plot(pto1(1), pto1(2), '+b')
hold on
plot(pto2(1), pto2(2), '.b')
hold on
plot(line_xy(:,1), line_xy(:,2), 'm') % Pintamos iterativamente las lineas
% Extend the line
factor_distance = 1.2;
theta = atan2(pto2(2) - pto1(2), pto2(1) - pto1(1)); % rad
pto2_update(1) = pto2(1) + ( factor_distance * cosd(theta) );
pto2_update(2) = pto2(2) + ( factor_distance * sind(theta) );
% Update new points in line
[line_x,line_y]=fillline(pto1(1,:), pto2_update(1,:),100);
line_xy = [line_x' line_y'];
figure
plot(pto1(1), pto1(2), '+b')
hold on
plot(pto2(1), pto2(2), '.b')
hold on
plot(line_xy(:,1), line_xy(:,2), 'm')
Thank you for any help in advance.
0 Comments
Accepted Answer
John D'Errico
on 27 May 2018
Edited: John D'Errico
on 27 May 2018
Why do you need filline, or anything like it? And why are you worrying about angles, etc.? You are making this far more complex than it ever needs to be.
Lets just write it from scratch. Given two points, call them as you did...
pto1 = [3.4353 0.2521];
pto2 = [39.5904 -20.6633];
% A vector along the ray from pto1 to pto2...
V = pto2 - pto1;
% The distance between the points would be:
% dist12 = norm(V);
% but there is no need to compute it.
% which will be extended (by 20% in this case) here
factor_distance = 1.2;
% Extend the ray
pext = pto1 + V*factor_distance;
% plot...
plot([pto1(1),pto2(1)],[pto1(2),pto2(2)],'bo',[pto1(1),pext(1)],[pto1(2),pext(2)],'r-')
2 Comments
sloppydisk
on 27 May 2018
I would still advice you to just use linspace to populate the lines as it's much more elegant and easier to understand.
More Answers (1)
sloppydisk
on 27 May 2018
I would first read the documentation before grabbing stuff off file exchange if I were you, because the fillline is really not necessary and there's much easier ways of plotting points. For example:
% Points
pts = zeros(2);
pts(1:2) = [1 2];
v = [2 3];
pts(3:4) = pt1 + v;
x = pts(1, :); y = pts(2, :);
plot(x, y, '-+')
% Extend the line
factor = 1.2;
pts(3:4) = pt1 + factor*v;
x = pts(1, :); y = pts(2, :);
hold on
plot(x, y, '-+')
hold off
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!