gusucode.com > 《精通matlab 7》包括配套光盘 > 配套光盘里的程序附件/Ex-10/myisintri.m

    function y=myisintri(A,M)
%Determine whether point M is in triangle A or not.
%A makes the triangle,A is a 3*2 matrix
%M makes the point,M is a 1*2 vector

%y=1 means M lies in the triangle determined by A.
%y=0 means M lies on the edge of triangle determined by A.
%y=-1 means M lies out of the triangle determined by A.

%---------method 1-------------------
% x1=A(1,1);y1=A(1,2);
% x2=A(2,1);y2=A(2,2);
% x3=A(3,1);y3=A(3,2);
% x0=M(1);y0=M(2);
% if and(((x0-x1)*(y2-y1)-(x2-x1)*(y0-y1))*((x0-x1)*(y3-y1)-(x3-x1)*(y0-y1))<0,((x0-x2)*(y1-y2)-(x1-x2)*(y0-y2))*((x0-x2)*(y3-y2)-(x3-x2)*(y0-y2))<0)
%     y=1;
% elseif or(((x0-x1)*(y2-y1)-(x2-x1)*(y0-y1))*((x0-x1)*(y3-y1)-(x3-x1)*(y0-y1))==0,((x0-x2)*(y1-y2)-(x1-x2)*(y0-y2))*((x0-x2)*(y3-y2)-(x3-x2)*(y0-y2))==0)
%     y=0;
% else
%     y=-1;
% end
%---------method 1 end----------------

%---------method 2--------------------
%assign the coordinates of the three points
x1=A(1,1);y1=A(1,2);
x2=A(2,1);y2=A(2,2);
x3=A(3,1);y3=A(3,2);
%assigh the coordinates of the target points
x0=M(1);y0=M(2);
%Determine the relationship between point M and triangle A
if and(((M(1)-A(1,1))*(A(2,2)-A(1,2))-(A(2,1)-A(1,1))*(M(2)-A(1,2)))*((M(1)-A(1,1))*(A(3,2)-A(1,2))-(A(3,1)-A(1,1))*(M(2)-A(1,2)))<0,((M(1)-A(2,1))*(A(1,2)-A(2,2))-(A(1,1)-A(2,1))*(M(2)-A(2,2)))*((M(1)-A(2,1))*(A(3,2)-A(2,2))-(A(3,1)-A(2,1))*(M(2)-A(2,2)))<0)
    y=1;
elseif or(((M(1)-A(1,1))*(A(2,2)-A(1,2))-(A(2,1)-A(1,1))*(M(2)-A(1,2)))*((M(1)-A(1,1))*(A(3,2)-A(1,2))-(A(3,1)-A(1,1))*(M(2)-A(1,2)))==0,((M(1)-A(2,1))*(A(1,2)-A(2,2))-(A(1,1)-A(2,1))*(M(2)-A(2,2)))*((M(1)-A(2,1))*(A(3,2)-A(2,2))-(A(3,1)-A(2,1))*(M(2)-A(2,2)))==0)
    y=0;
else
    y=-1;
end
%plot the triangle A and the M point
plot([A(:,1);A(1,1)],[A(:,2);A(1,2)],'r',M(1),M(2),'b*');
%----------method 2 end---------------