InquisitiveCoder
InquisitiveCoder

Reputation: 171

Extend a line through 3 points matlab

Im just trying to draw a line through the following points in matlab. Currently the line extends only to the points. I need to to extend and intercept the x axis. The code is below

A = [209.45 198.066 162.759];
B = [1.805 1.637 1.115]; 
plot(A,B,'*');
axis([0 210 0 2]);
hold on
line(A,B)
hold off

Upvotes: 0

Views: 658

Answers (1)

If you want to augment your points with a corresponding y==0 point, I suggest using interp1 to obtain the x-intercept:

A = [209.45 198.066 162.759];
B = [1.805 1.637 1.115];

x0 = interp1(B,A,0,'linear','extrap'); %extrapolate (y,x) at y==0 to get x0
[newA, inds] = sort([x0 A]); %insert x0 where it belongs
newB = [0 B];
newB = newB(inds); %keep the same order with B

plot(A,B,'b*',newA,newB,'b-');

This will use interp1 to perform a linear interpolant, with extrapolation switched on. By interpolating (B,A) pairs, we in effect invert your linear function.

Next we add the (x0,0) point to the data, but since matlab draws lines in the order of the points, we have to sort the vector according to x component. The sorting order is then used to keep the same order in the extended B vector.

Finally the line is plotted. I made use of plot with a linespec of '-' to draw the line in the same command as the points themselves. If it doesn't bother you that the (x0,0) point is also indicated, you can plot both markers and lines together using plot(newA,newB,'*-'); which ensures that the colors match up (in the above code I manually set the same blue colour on both plots).

Upvotes: 2

Related Questions