check if two polygons of n sides intersect in matlab

There are different algorithms to check if two polygons intersect, but one common and efficient way to accomplish this in Matlab is to use the polybool function. This function can operate on two closed polygons and determine if their intersection is not empty, and if so, return the resulting polygon(s).

Here is an example code showing how to use polybool to check the intersection of two polygons defined by their vertices:

main.m
% Define the vertices of the first polygon:
x1 = [1 3 5 6 4 2];
y1 = [1 1 2 4 5 4];
p1 = [x1' y1'];  % format vertices matrix as Nx2 array

% Define the vertices of the second polygon:
x2 = [3 4 5 4];
y2 = [3 4 3 2];
p2 = [x2' y2'];

% Use polybool to compute the intersection of the two polygons:
[xint, yint] = polybool('intersection', x1, y1, x2, y2);

% If xint and yint are empty, then the polygons do not intersect:
if isempty(xint) || isempty(yint)
    disp('Polygons do not intersect')
else
    disp('Polygons intersect')
    % Here you can do something with the intersection points:
    pint = [xint' yint'];
end
622 chars
22 lines

Note that polybool can also be used to compute the union, difference, or xor of the two polygons.

related categories

gistlibby LogSnag