Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a line through two points

Tags:

plot

matlab

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.

like image 582
CodeFusionMobile Avatar asked Oct 30 '12 16:10

CodeFusionMobile


People also ask

Is it always possible to draw a line through 2 points?

Two points are always collinear since we can draw a distinct (one) line through them. Three points are collinear if they lie on the same line.

How do you find the equation of a line with two coordinates?

The straight line through two points will have an equation in the form y = m x + c . We can find the value of , the gradient of the line, by forming a right-angled triangle using the coordinates of the two points.


1 Answers

  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.

like image 128
Gunther Struyf Avatar answered Oct 21 '22 13:10

Gunther Struyf