在这个代码中,我将一条线分割成不同的部分,如何在每个线段点绘制一条长度为+/-5(点上和点下(的垂线,并获得每条线的终点坐标?
代码:
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
这最终是一个代数问题。你知道你想要的线的斜率,perpSlope = -1/m
;你知道";原点";对于所需的每条线段,xy = (1-t)*xy1 + t*xy2;
。
您可以做的是首先,通过原点(0,0(绘制您想要的线。使用勾股定理计算直线的终点到您想要的长度:
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
您将得到:new_x = +- 5 / sqrt(m^2 - 1)
,两个new_x
的坐标作为新坡度的函数。
然后根据两个new_x
的值来求解new_y
的值:new_y = m * new_x
。现在,您有了一组要通过原点绘制的直线的坐标。
最后,要获得通过每个点绘制的坐标集,只需将这些点的值xy
添加到新坐标中即可。
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
回顾:
当直线位于(0,0(时,计算新的x:new_x = [5/sqrt(perpSlope^2-1), -5/sqrt(perpSlope^2-1)];
为这些新的x计算新的y:new_y = perpSlope*new_x;
根据新坐标计算并绘制新线:
for i = 1:length(xy)
line( new_x + xy(i,1), new_y + xy(i,2) )
end
注意:这将绘制在旧图形的顶部,因此首先使用命令hold on
编辑:此方法不适用于垂直/水平线,因为那里的斜率分别为无穷大和零。但这些案例应该非常简单。例如:
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