MATLAB Answers


How to draw a perpendicular line using a point and slope

Hessa Alali さんによって質問されました 2019 年 3 月 24 日
最新アクティビティ Hessa alali さんによって コメントされました 2019 年 4 月 2 日
I have a line between two point, P1=[374 448] and P2=[385 562]. i want to find a perpendicular line to the original line passing throw the middle point of the original line.

  0 件のコメント

サインイン to comment.

3 件の回答

John D'Errico
回答者: John D'Errico
2019 年 3 月 24 日
編集済み: John D'Errico
2019 年 3 月 24 日

You want to "find" it? Or you want to draw it?
The midpoint of the line segment is at
(P1 + P2)/2
ans =
379.5 505
Y is irrelevant there, since you are asking about a VERTICAL line, thus a line with infinite slope. The line is described by the simple equation X = 379.5. Y takes on any value you wish.
How to draw that line? This will suffice.
xline((P1(1) + P2(1))/2)
xline was introduced in R2018b.

  3 件のコメント

Hessa Alali 2019 年 3 月 24 日
can i use m1*m=-1 to find perpendicular line slope, where m1 is perpendicular line slope and m is slope of original line?
Hessa Alali 2019 年 3 月 24 日
xline doesn't work for me
2019 年 3 月 24 日
Do you mean you get an error using xline (possibly due to using an older release than R2018b), or do you mean you don't get the expected output? In the former case, provide details about the error and about what Matlab version you're using. In the latter case, explain how the result is different from what you expect.

サインイン to comment.

Image Analyst
回答者: Image Analyst
2019 年 3 月 24 日

Try this:
P1=[374 448]
P2=[385 562]
p1x = P1(1);
p1y = P1(2);
p2x = P2(1);
p2y = P2(2);
plot([p1x, p2x], [p1y, p2y], 'ro-', 'LineWidth', 2);
grid on;
xlabel('x', 'FontSize', 15);
ylabel('y', 'FontSize', 15);
% Find midpoint
midX = mean([p1x, p2x])
midY = mean([p1y, p2y])
hold on;
plot(midX, midY, 'r*', 'LineWidth', 2, 'MarkerSize', 25);
% Get the slope
slope = (p2y-p1y) / (p2x-p1x)
% For perpendicular line, slope = -1/slope
slope = -1/slope
% Point slope formula (y-yp) = slope * (x-xp)
% y = slope * (x - midX) + midY
% Compute y at some x, for example at x=300
x = 300
y = slope * (x - midX) + midY
plot([x, midX], [y, midY], 'bo-', 'LineWidth', 2);
axis equal
0001 Screenshot.png

  1 件のコメント

Hessa alali 2019 年 4 月 2 日
I used this method and it works fine.
But when i applied it in an image, it doesn't gave me a perpendicular line.
does the image have a difference in their axis ? x and y?

サインイン to comment.

Star Strider
回答者: Star Strider
2019 年 3 月 24 日

Try this:
P1=[374 448];
P2=[385 562];
P12 = [P1;P2];
mP12 = mean(P12);
b = [P12(:,1) ones(2,1)] \ P12(:,2); % Equation Of Initial Line
PLv = [-1/b(1); mP12(2)+mP12(1)/b(1)]; % Equation Of Perpendicular Line
PL = [P12(:,1) ones(2,1)] * PLv; % Coordinates OF Perpendicular Line
plot(P12(:,1), P12(:,2))
hold on
plot(P12(:,1), PL)
hold off
axis equal
Note that even though the second line is perpendicular to the first line, it will not appear to be perpendicular unless you use the:
axis equal

  0 件のコメント

サインイン to comment.

Translated by