2017-05-04 74 views
2

我有一些数据点,可以很容易地在MATLAB图中绘制它们。测试点是否在矩形内

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

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

数据采样点和矩形:

Sample data points and rectangles

+0

使用“inpolygon”功能。 – Ozcan

+0

@Ozcan非常感谢。这就是我想要的!我甚至无法猜测这样的功能存在! – Mechatronics

+0

你可以在这里查看MATLAB的函数列表:https://www.mathworks.com/help/matlab/functionlist.html – Ozcan

回答

3

由于奥兹坎在评论中说,inpolygon是要走的路。这里有一个快速演示,看评论的细节:

% 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'); 

结果:

plot


注意你现在有逻辑矩阵inrect,这是真的(每长方形一列,当点位于矩形内时,每点有一行)。上面的代码使用any运算符绘制点的长方形的任何。