正如 Ozcan 在 cmets 中所说,inpolygon 是要走的路。这是一个快速演示,详情见 cmets:
% Create 4 random rectangles, defined by their x and y coords in rectX and rectY.
% Each column defines a different rectangle.
sizes = randi([5,10], 2, 4)./10;
rectX = randi([1,5], 1, 4); rectX = [rectX; rectX; rectX + sizes(1,:); rectX + sizes(1,:)];
rectY = randi([1,5], 1, 4); rectY = [rectY; rectY + sizes(2,:); rectY + sizes(2,:); rectY];
% Create a random set of 1000 points for testing
points = [rand(1000, 1)*range(rectX(:))+min(rectX(:)), rand(1000, 1)*range(rectY(:))+min(rectY(:))];
% Set up logical matrix of test results
inrect = logical(zeros(size(points,1), size(rectX,2)));
% Plot the rectangles using patch
figure;
patch(rectX,rectY,'red')
% Hold on and plot all of the points as black dots
hold on;
plot(points(:,1),points(:,2),'.k');
% Loop through each rectangle, testing the points
for r = 1:size(rectX, 2)
% Test points using inpolygon, store results to inrect matrix
inrect(:,r) = inpolygon(points(:,1), points(:,2), rectX(:,r), rectY(:,r));
end
% Plot all points which are in any rectangle as blue circles
plot(points(any(inrect,2), 1), points(any(inrect,2), 2), 'bo');
结果:
请注意,您现在有逻辑矩阵inrect,当点位于矩形内时,这是正确的(每个矩形一列,每个点一行)。上面的代码使用any 操作符来绘制点在任意 个矩形中的情况。