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@inrae.fr 0034 % Created: 2009-06-19, using Matlab 7.7.0.471 (R2008b) 0035 % Copyright 2009-2024 INRA - Cepia Software Platform 0036 0037 % In case of a multiple polygon, decompose into a set of contours, and 0038 % performs test for each contour 0039 if iscell(poly) || any(isnan(poly(:))) 0040 % transform as a cell array of simple polygons 0041 polygons = splitPolygons(poly); 0042 N = length(polygons); 0043 Np = size(point, 1); 0044 0045 % compute orientation of polygon, and format to have Np*N matrix 0046 areas = zeros(N, 1); 0047 for i = 1:N 0048 areas(i) = polygonArea(polygons{i}); 0049 end 0050 ccw = areas > 0; 0051 ccw = repmat(ccw', Np, 1); 0052 0053 % test if point inside each polygon 0054 in = false(size(point, 1), N); 0055 for i = 1:N 0056 poly = polygons{i}; 0057 in(:, i) = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2)); 0058 end 0059 0060 % count polygons containing point, weighted by polygon orientation 0061 b = sum(in.*(ccw==1) - in.*(ccw==0), 2) > 0; 0062 0063 else 0064 % standard test for simple polygons 0065 b = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2)); 0066 end