How can I determine is (x,y) pair is inside an orthogonal area?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
gsourop
am 17 Dez. 2018
Bearbeitet: John D'Errico
am 17 Dez. 2018
Hi everyone,
Suppose we have an orthogonal area where the 4 x,y pairs are (1,5) , (3,5) , (1,7) and (3,7). I would like to test if a random pair, such as (0,6), is inside the orthogonal area. I did the following code but I don't get any answer:
x = [1, 3];
y = [5, 7];
x0 = 0;
y0 = 6;
if x0 < x(2)
if x0 > x(1)
if y0 < y(2)
if y0 > y(1)
answer0 == 1
else
answer0 == 0
end
end
end
end
0 Kommentare
Akzeptierte Antwort
Rik
am 17 Dez. 2018
Bearbeitet: Rik
am 17 Dez. 2018
Your else statement is only reached in the inner part. If you want to use this structure, you should do the following:
x = [1, 3];
y = [5, 7];
x0 = 0;
y0 = 6;
answer0 =false;
if x0 < x(2)
if x0 > x(1)
if y0 < y(2)
if y0 > y(1)
answer0 = true;
end
end
end
end
However, a more compact/clearer way is this:
x = [1, 3];
y = [5, 7];
x0 = 0;
y0 = 6;
if x0>min(x) && x0<max(x) && ...
y0>min(y) && y0<max(y)
answer0=true;
else
answer0=false;
end
1 Kommentar
Stephen23
am 17 Dez. 2018
The if - else is not required:
answer0 = x0>min(x) && x0<max(x) && y0>min(y) && y0<max(y)
Weitere Antworten (1)
John D'Errico
am 17 Dez. 2018
Bearbeitet: John D'Errico
am 17 Dez. 2018
A better solution, rather than such nested, specific tests, is to use a tool like inpolygon. Make sure they are sorted, so it truly represents a polygon, in that order. But the points are easily sorted in terms of angle.
px = [1 , 3 , 3 , 1];
py = [5 , 5 , 7, 7];
inpolygon(2,6,px,py)
ans =
logical
1
In newer releases of MATLAB, we also have the polyshape tools.
PS = polyshape(px,py)
PS =
polyshape with properties:
Vertices: [4×2 double]
NumRegions: 1
NumHoles: 0
isinterior(PS,2,6)
ans =
logical
1
The nice thing about inpolygon and polyshape is these tools are not restricted to simple rectangular, 90 degree polygons.
So, if your points are not known to lie in a good order to represent a polygon, we could convert to polar coordinates, and then sort the sequence of points around the centroid. Simpler is to just use a convex hull to do the heavy thinking for you. So if I swap points 3 and 4, so the polygon turns into sort of a figure 8, we can easily recover a proper order:
px = [1 , 3 , 1, 3];
py = [5 , 5 , 7, 7];
edgelist = convhull(px,py)
edgelist =
1
2
4
3
1
PX = px(edgelist)
PX =
1 3 3 1 1
PY = py(edgelist)
PY =
5 5 7 7 5
So even though the points in px and py were mi-sorted, convhull reordered them. It also connected the polygon, so the first and last point were the same, but tools like inpolygon and polyshape won't care.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Elementary Polygons finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!