Perpendicular line at each segment point - Matlab

Viewed 242

In this code, I segment a line to different sections, How can I plot a perpendicular line at each segment point with a length of +/-5 (above and below the point) and get the end coordinates of each line?

Code:

clc;
clear all;
close all;


%Init coords
x1 = 0
y1 = 3
x2 = 4
y2 = 4

%Convert to xy coords
xy1 = [x1, y1];
xy2 = [x2, y2];

n = 10;
t = linspace(0,1,n+1)';
xy = (1-t)*xy1 + t*xy2;
plot(xy(:,1),xy(:,2),'b-o')

%Calc. slope
m = (xy2(2)-xy1(2))/(xy2(1)-xy1(1)); %m = (y2-y1)/(x2-x1);
perpSlope = -1/m 
1 Answers

This is ultimately an algebra problem. You know the slope of the lines you want, perpSlope = -1/m; and you know the "origin points" for each segment lines you want, xy = (1-t)*xy1 + t*xy2;.


What you can do is first, draw the line you want through the origin (0,0). Calculate the end point of your line to the length you want, using the Pythagorean theorem:

5^2 = x^2 + y^2 -- Pythagorean theorem, length of your line is +-5
y = sqrt( 5^2 - x^2 ) -- Solved for y

y = mx + b -- Equation of a straight line
sqrt( 5^2 - x^2 ) = mx + 0 -- Substitute the above into y, and solve for x | b==0 for the origin

You will get: new_x = +- 5 / sqrt(m^2 - 1), the coordinates for the two new_x as a function of the new slope.

Then you solve for the new_y values, based on the two new_x's: new_y = m * new_x. Now you have one set of coordinates of the line you want drawn through the origin.

Finally, to get the sets of coordinates drawn through each of the points you have, you just add the values of those points xy to the new coordinates.

for i = 1:numOfPoints
    % This assumes xy is in the format: [x1, y1; x2, y2; ...]
    % i.e. The first column are x coordinates, the second column are y coordinates
    line_x = new_x + xy(i,1) 
    line_y = new_y + xy(i,2)
    line(line_x, line_y)
end

To recap:

Calculate new x's when the line is at (0,0): new_x = [5/sqrt(perpSlope^2-1), -5/sqrt(perpSlope^2-1)];

Calculate new y's for those new x's: new_y = perpSlope*new_x;

Calculate and draw new lines based on the new coordinates:

for i = 1:length(xy)
    line( new_x + xy(i,1), new_y + xy(i,2) )
end

Note: this will draw on top of your old graph, so use the command hold on first


Edit: This method will not work for vertical/horizontal lines, since the slopes there are infinite and zeros, respectively. But those cases should be very simple to program for. E.g.:

if isinf(m) % Original line is vertical
    line_x = [xy(i,1)+5, xy(i,1)-5]; % +- 5 to x axis
    line_y = [xy(i,2)  , xy(i,2)];   % No change to y axis
    line(line_x, line_y)
end

if m == 0 % Original line is horizontal
    line_x = [xy(i,1)  , xy(i,1)];   % No change to x axis
    line_y = [xy(i,2)+5, xy(i,2)-5]; % +- 5 to y axis
    line(line_x, line_y)
end
Related