Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Topic: Can matlab determine if a point inside a polygon?
Replies: 7   Last Post: Jun 21, 2013 3:29 AM

 Messages: [ Previous | Next ]
 Matt J Posts: 4,997 Registered: 11/28/09
Re: Can matlab determine if a point inside a polygon?
Posted: Jun 3, 2010 12:24 AM

Sang-Ho Yun <Sang-Ho.Yun@jpl.nasa.gov> wrote in message <C82C761E.6F1B%Sang-Ho.Yun@jpl.nasa.gov>...
> Can we make matlab decide if a point on a plane is inside a closed polygon?
> How do we know if a point is inside or outside the polygon?

==========

For convex polygon's see the routine below. It should be faster than inpolygon because it exploits the convex structure.

function [A,b]=vert2con_special(a)
%Finds the expression of a 2D convex polygon as a set of linear inequalities from
%a set of vertices
%
% [A,b]=vert2con_special(a)
%
%in:
%
% a: Nx2 matrix whos rows are polygon vertex coordinates. The rows must
% must be ordered so that adjacent rows correspond to adjacent vertices
% (which will trivially be the case for triangles).
%
%out:
%
% [A,b]: Nx1 vector and Nx2 matrix such that A*x<=b if and only if x is a point
% inside the polygon
%
%
%Example: Detect whether a point is in a triangle
%
% %%%data
% Vertices=[0 0; 1 0; 0 1]; %vertices of a triangle
% p1=[.5;.25]; %a point inside the triangle
% p2=[.5;-.25];%a point outside the triangle
%
% [A,b]=vert2con_special(Vertices);
%
% >>all(A*p1<=b) %Test if p1 is in the triangle.
%
% ans =
%
% 1
%
% >>all(A*p2<=b) %Test if p2 in the triangle.
%
% ans =
%
% 0

centroid=mean(a).';
R=[0 1; -1 0];

A=diff([a;a(1,:)])*R;

b=sum(A.*a,2);

ii=(A*centroid>=b);

b(ii)=-b(ii);
A(ii,:)=-A(ii,:);

Date Subject Author
6/2/10 Sang-Ho Yun
6/3/10 Derek Goring
6/3/10 Walter Roberson
6/3/10 Matt J
11/7/12 Evan00
6/21/13 sh
6/21/13 Torsten
6/21/13 sh