matlab - 每个线段点的垂直线 - Matlab

标签 matlab

在这段代码中,我将一条线分割成不同的部分,如何在每个分割点处绘制一条长度为+/-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 = m * new_x 求解 new_y 值。现在您有了一组想要通过原点绘制的线的坐标。

最后,要获得通过每个点绘制的坐标集,只需将这些点的值 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

关于matlab - 每个线段点的垂直线 - Matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62965874/

相关文章:

以元组为键的 MATLAB containers.Map

python - (/bin/bash : python3: command not found) When running python script through system command in Matlab

mysql - MATLAB 7.0与MYSQL的连接

Matlab - 周围元素的总和

python - Python 中的多元线性回归 - MATLAB 中 mvregress 的模拟?

matlab - 向量的平均非连续段

matlab - fvtool生成的数字亲子关系破裂?

matlab - 连接结构 : Update struct fields without overwriting existing fields

matlab - 在交互式经纪商上计算 IV60 和 IV90

matlab - 检查 caller == MATLAB 中的基础工作区