ISPOINTINPOLYGON Test if a point is located inside a polygon. B = isPointInPolygon(POINT, POLYGON) Returns true if the point is located within the given polygon. This function is simply a wrapper for the function inpolygon, to avoid decomposition of point and polygon coordinates. Example pt1 = [30 20]; pt2 = [30 5]; poly = [10 10;50 10;50 50;10 50]; isPointInPolygon([pt1;pt2], poly) ans = 1 0 poly = [0 0; 10 0;10 10;0 10;NaN NaN;3 3;3 7;7 7;7 3]; pts = [5 1;5 4]; isPointInPolygon(pts, poly); ans = 1 0 See also points2d, polygons2d, inpolygon, isPointInTriangle
0001 function b = isPointInPolygon(point, poly) 0002 %ISPOINTINPOLYGON Test if a point is located inside a polygon. 0003 % 0004 % B = isPointInPolygon(POINT, POLYGON) 0005 % Returns true if the point is located within the given polygon. 0006 % 0007 % This function is simply a wrapper for the function inpolygon, to avoid 0008 % decomposition of point and polygon coordinates. 0009 % 0010 % Example 0011 % pt1 = [30 20]; 0012 % pt2 = [30 5]; 0013 % poly = [10 10;50 10;50 50;10 50]; 0014 % isPointInPolygon([pt1;pt2], poly) 0015 % ans = 0016 % 1 0017 % 0 0018 % 0019 % poly = [0 0; 10 0;10 10;0 10;NaN NaN;3 3;3 7;7 7;7 3]; 0020 % pts = [5 1;5 4]; 0021 % isPointInPolygon(pts, poly); 0022 % ans = 0023 % 1 0024 % 0 0025 % 0026 % 0027 % See also 0028 % points2d, polygons2d, inpolygon, isPointInTriangle 0029 0030 % 0031 % ------ 0032 % Author: David Legland 0033 % e-mail: david.legland@inra.fr 0034 % Created: 2009-06-19, using Matlab 7.7.0.471 (R2008b) 0035 % Copyright 2009 INRA - Cepia Software Platform. 0036 0037 % HISTORY 0038 % 2013-04-24 add support for multiply connected polygons 0039 0040 % In case of a multiple polygon, decompose into a set of contours, and 0041 % performs test for each contour 0042 if iscell(poly) || any(isnan(poly(:))) 0043 % transform as a cell array of simple polygons 0044 polygons = splitPolygons(poly); 0045 N = length(polygons); 0046 Np = size(point, 1); 0047 0048 % compute orientation of polygon, and format to have Np*N matrix 0049 areas = zeros(N, 1); 0050 for i = 1:N 0051 areas(i) = polygonArea(polygons{i}); 0052 end 0053 ccw = areas > 0; 0054 ccw = repmat(ccw', Np, 1); 0055 0056 % test if point inside each polygon 0057 in = false(size(point, 1), N); 0058 for i = 1:N 0059 poly = polygons{i}; 0060 in(:, i) = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2)); 0061 end 0062 0063 % count polygons containing point, weighted by polygon orientation 0064 b = sum(in.*(ccw==1) - in.*(ccw==0), 2) > 0; 0065 0066 else 0067 % standard test for simple polygons 0068 b = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2)); 0069 end