How to draw a perpendicular line?

13 次查看(过去 30 天)
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
Image Analyst 2019-12-26
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 个评论
Image Analyst
Image Analyst 2019-12-27
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
0000 Screenshot.png
See the red line is perpendicular to the original blue line.
Andreea Stanescu
Andreea Stanescu 2019-12-27
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. :)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 NaNs 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by