利用matlab求点到直线距离和垂足坐标

方法1:

%    0======================================================0
%      本程序作用:利用matlab求点到直线距离和垂足坐标
%    
%    0======================================================0

clc
clear
close all;
%%%%%%%%%%%%%%%%%%%%%以下为主程序
 
%%%%%%%%%%%%%A、B点构成向量AB;C为任一点
A = [8*rand(1,1);8*rand(1,1)];%向量1A 点
B = [8*rand(1,1);8*rand(1,1)];%向量1B 点
C = [8*rand(1,1);8*rand(1,1)];
%%%%%%%%%%%%%A、B点构成向量AB;C为任一点
 
AngBAC = acosd((norm(A-B)^2+norm(A-C)^2-norm(B-C)^2)/(2*(norm(A-B)*norm(A-C))));%角A
AngABC = acosd((norm(B-A)^2+norm(B-C)^2-norm(A-C)^2)/(2*(norm(B-A)*norm(B-C))));%角B
if AngBAC>AngABC || AngBAC==AngABC
    AA = B; 
    BB = A; 
    C2ABJvLi = norm(AA-C) * sind(AngABC);
    D = [cosd(0),sind(0); -sind(0),cosd(0)]...
        *((BB - AA).* ((norm(AA-C) * cosd(AngABC)) / norm(A-B))) + AA;
else
    C2ABJvLi = norm(A-C) * sind(AngBAC);
    D = [cosd(0),sind(0); -sind(0),cosd(0)]...
        *((B - A).* ((norm(A-C) * cosd(AngBAC)) / norm(A-B))) + A;
end
clear AA BB AngBAC AngABC ;
%%%%%%%%%%%%%%%%%%%%%以上为主程序(结果为:C2ABJvLi--C点到向量AB的垂直距离;D--垂足坐标)
 
%%%%%%%%%%%%%%%%%%%%%画图
hold on;
plot([A(1),B(1)],[A(2),B(2)],'k');
plot([C(1),D(1)],[C(2),D(2)],'r');
plot(D(1),D(2),'*');
axis([-2,8,-2,8]);

 

结果(看上去有点不垂直,但实际计算CD垂直AB):

 

 

 说明:更改A、B、C坐标即可(坐标以列向量表示,第一行为x坐标,第二行为y)

方法2:

k = 0.5; % slope
b = 1; % interception
x1 = 3;
y1 = 2;

x2 = (k*y1+x1-k*b)/(1+k*k);
y2 = k*x2+b;

figure
hold on
plot(x1,y1,'ro')
plot(x2,y2,'r.','MarkerSize',15)
plot(0:0.01:abs(x2), k*(0:0.01:abs(x2))+b, 'b-')
plot([x1,x2],[y1,y2],'k-')
axis equal
hold off

disp([x2,y2])

 

posted on 2022-05-16 08:36  一杯明月  阅读(1558)  评论(0编辑  收藏  举报