Hi, I'm trying to find if certain points are inside or outside a polygon. I have a polygon file of a list of coordinates, and then have another file with a list of coordinates of points (some of which are inside the polygon, other are outside). The code I have written is as follows:
%Compare point coordinates
ystar = starcoordinates(:,2);
Srows = numel(textread('starcoordinates.txt','%1c%*[^\n]'));
%set initial values
Nint = 0;
%Loop through points for h=1:Srows;
for k=1:Nrows; if k==Nrows %end point+1 is the same as 1st point i=Nrows; j=1; else %Otherwise use the current point i=k; j=k+1; end
V = sort(square(:,1)); xmin = V(1); xmax = V(Nrows); Z = sort(square(:,2)); ymin = Z(1); ymax = Z(Nrows);
% Find points between minimum and maximum values if ystar(h) <= ymin Nint = 0; elseif ystar(h) >= ymax Nint = 0; if xstar(h) >= xmax Nint = 0; elseif xstar(h) < xmin Nint = 0;
%Point is within minima and maxima %check
else Bp=((y(j)-y(i))/(x(j)-x(i))); Ap=(y(j)-(Bp.*x(i))); Yp = Ap + (Bp.*Xp); Xp = (ystar(h)-Ap).*(1/Bp); if xstar(h) <= Xp Nint = Nint + 1; end end end end
Ntot = ((floor(Nint/2)).*2)-Nint;
%Ntot=0 if Nint=even number, Ntot=-1 if Nint=odd number %if -1 point is inside the polygon, if 0 point is outside the polygon if Ntot == 0 ; disp = 'star is outside the cloud' else Ntot == -1; disp = 'star is inside the cloud' end end
It's telling me that all the points are outside the polygon so is taking all Ntot to be 0, I think. If anyone can help me solve this problem and see what is wrong in my code it would save my life!!!
No products are associated with this question.
I think one should be able to easily do a simple inequality and find out of a point is outside or inside a closed curve. Here's my idea, for example for a circle with radius 1, and centered at origin, if you want to know if the point (x,y) is inside it or outside, you can do x^2+y^2<1 or x^2+y^2>1. for a square with each side equal to sqrt(2) and centered at origin but rotated 45 deg you can do the comparison abs(x)+abs(y)>1 or abs(x)+abs(y)<1. Offcourse if the length of the side of the equare (or radius of circle) is different you can do a simple transformation and change that 1 to proper number. Or if the shape is are not centered at origin you can do a transformation (translation) on the points as well as the shape to bring the shapre to origin. Or if you want to change the angle or orientation of the shape (like as for square) you need to rotate all the points (transformation again) to get that rotated shape.
The hardest step would be to find the quation of the polygon you are looking for and write the proper inquality.
If it's a convex polygon, a possibly faster approach than INPOLYGON is to use this FEX file to express the polygon in terms of linear inequalities
Then, to see if a particular x0 lies in the polygon, do
isinside = all(A*x0<=b,1);