【问题标题】:Test if points are within rectangles测试点是否在矩形内
【发布时间】:2017-05-04 05:14:51
【问题描述】:

我有一些数据点,可以在 MATLAB 中轻松地将它们绘制成图形。

我需要找出哪些数据点位于某些矩形区域内,如附图所示。在这张图片中,黑点代表我的数据点,红色矩形代表提到的区域。

如何搜索我的数据点并查看它们是否属于任何矩形?我需要为每个矩形列出所有成员(数据点)。

样本数据点和矩形:

【问题讨论】:

  • 使用“多边形”函数。
  • @Ozcan 非常感谢。这就是我想要的!我什至无法猜测存在这样的功能!
  • 您可以在这里查看 MATLAB 的函数列表:mathworks.com/help/matlab/functionlist.html
  • @Ozcan 我总是这样做,而且我是 MATLAB 的大师,但这个功能很棒。没见过。

标签: matlab matlab-figure


【解决方案1】:

正如 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 操作符来绘制点在任意 个矩形中的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    相关资源
    最近更新 更多