MATLAB判断一个点是否在多边形内部,比inpolygon更健壮
matlab中提供了判断一个点是否在多边形内部的函数inpolygon,但是这个函数存在与polyarea类似的问题,即要求定义多边形的点必须是沿着多边形连续的,而这在很多时候很难保证。采用类似的思想,我对这个函数进行了适当改造,其健壮性立见提高。
函数 myinpolygon.m
function flag = myinpolygon(X,Y,xv,yv) % decide if the points are inside or outside the polygon % Input: % X: x-coordinations of the points to be detected % Y: y-coordinations of the points to be detected % xv: x-coordinations of the vertex define the polygon % yv: y-coordinations of the vertex define the polygon % Output: % flag=1: inside the polygon % flag=0: outside the polygon % Poweed by Xianbao Duan % Email: xianbao.d@gmail.com % Website: http://www.52souji.net/ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % log: % 2012-05-07: Complete % 2012-05-18: Modify the comments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% vertex(:,1) = xv; vertex(:,2) = yv; % generate the Delaunay Triangle dt = DelaunayTri(vertex); % calculate the volumn of the body k = convexHull(dt); xv2 = dt.X(k(1:(end-1)),1); yv2 = dt.X(k(1:(end-1)),2); flag = inpolygon(X,Y,xv2,yv2);
健壮性测试
>> a=[-5 0;5 0;0 -5; 0 5]; >> inpolygon(1,1,a(:,1),a(:,2)) ans = 0 >> myinpolygon(1,1,a(:,1),a(:,2)) ans = 1
显然,输入的(1,1)应该是在有a定义的多边形内部,但是系统提供的inpolygon给出的结果却说不在;我改编的函数给出了正确的结果。
虽然只是小小的改动,在结果上却截然相反,足见其重要性。