# How to draw a perpendicular line?

22 views (last 30 days)
Andreea Stanescu on 26 Dec 2019
Commented: Andreea Stanescu on 27 Dec 2019
Hello! How can I draw a perpendicular line to another? I have the line it has to intersect defined by the following code:
% Get a known index. "known" because it's one of the training points. knownIndex = randperm(length(x), 1)
% Get a unknown index. "unknown" because it's one of the interpolated points. unknownIndex = randperm(length(finerSpacing), 1)
% Get the x,y coordinates for these indexes.
xKnown = knots(1, knownIndex)
yKnown = knots(2, knownIndex)
xUnknown = splineXY(1, unknownIndex)
yUnknown = splineXY(2, unknownIndex)
% Now draw a line between them in dark green.
darkGreen = [0, 0.5, 0];
plot([xKnown, xUnknown], [yKnown, yUnknown], 'o-', ... 'Color', darkGreen, 'MarkerSize', 24, 'LineWidth', 3);
legend('Knots', 'Spline', 'Line between random knot and random point');
The problem is that I can not make it so that the new line is perpendicular on the "known index". What can i do? Please help!

Image Analyst on 26 Dec 2019
The slope of a line perpendicular to another has a slope that is -1 over the slope of the other line. so
coefficients = polyfit(xKnown, yKnown, 1);
slope = coefficients(1);
Now get the min and max x where you want to draw the line.
[x1p, index1] = min(xKnown);
[x2p, index2] = max(xKnown);
% Get y at those endpoints
y1p = yKnown(index1);
y2p = yKnown(index2);
% Compute the slope
perpSlope = -1 / slope;
% Equation of line going through the left most x (at x1p) is
% (y - y1p) = perpSlope * (x - x1p)
y1 = perpSlope * (x1p - xKnown(index1)) + y1p
y2 = perpSlope * (x2p - xKnown(index1)) + y1p
line([x1p, x2p], [y1, y2], 'Color', 'r')
It's untested code, so no guarantees.
##### 3 CommentsShow 1 older commentHide 1 older comment
Image Analyst on 27 Dec 2019
It seems to work fine for me. What did you do differently?
xKnown = sort(rand(1, 2), 'ascend')
yKnown = rand(1, 2)
plot(xKnown, yKnown, 'b.-', 'LineWidth', 2, 'MarkerSize', 25);
grid on;
coefficients = polyfit(xKnown, yKnown, 1);
slope = coefficients(1)
[x1p, index1] = min(xKnown)
[x2p, index2] = max(xKnown)
% Get y at those endpoints
y1p = yKnown(index1);
y2p = yKnown(index2);
% Compute the slope
perpSlope = -1 / slope
% Equation of line going through the left most x (at x1p) is
% (y - y1p) = perpSlope * (x - x1p)
y1 = perpSlope * (x1p - xKnown(index1)) + y1p
y2 = perpSlope * (x2p - xKnown(index1)) + y1p
line([x1p, x2p], [y1, y2], 'Color', 'r', 'LineWidth', 2)
hold on;
plot([x1p, x2p], [y1, y2], 'ro', 'LineWidth', 2, 'MarkerSize', 25)
axis equal
See the red line is perpendicular to the original blue line.
Andreea Stanescu on 27 Dec 2019
Thank you so much! I don't know why it didn't show. I will try and adapt this to my code and my known original point. :)