10
votes

Using MatLab, I know how to create a line segment connecting two points using this code:

line([0 1],[0 1])

This draws a straight line segment from the point (0,0) to the point (1,1).

What I am trying to do is continue that line to the edge of the plot. Rather than just drawing a line between these two points I want to draw a line through those two points that spans the entire figure for any set of two points.

For this particular line and a x=-10:10, y=-10:10 plot I could write:

line([-10 10], [-10 10]);

But I would need to generalize this for any set of points.

2

2 Answers

6
votes

What about

  function = long_line(X,Y,sym_len)
       dir = (Y-X)/norm(Y-X);
       Yp = X + dir*sym_len;
       Xp = X - dir*sym_len;
       line(Xp,Yp);
  end

being sym_len one half of the expected length of the plotted line around X?

11
votes
  1. Solve the line equation going through those two points:

    y = a*x + b;
    

    for a and b:

    a = (yp(2)-yp(1)) / (xp(2)-xp(1));
    b = yp(1)-a*xp(1);
    
  2. Find the edges of the plotting window

    xlims = xlim(gca);
    ylims = ylim(gca);
    

    or take a edges far away, so you can still zoomout, later reset the x/y limits.
    or if there is no plot at the moment, define your desired edges:

    xlims = [-10 10];
    ylims = [-10 10];
    
  3. Fill in those edges into the line equation and plot the corresponding points:

    y = xlims*a+b;
    line( xlims, y );
    
  4. And reset the edges

    xlim(xlims);
    ylim(ylims);
    

There is one special case, the vertical line, which you'll have to take care of separately.