MATLAB: How to draw a perpendicular line

90 degreelineperpendicularsquare

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!

Best Answer

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.