使用MATLAB识别不同扇形区域的点

时间:2016-03-22 00:53:47

标签: matlab coordinates geometry

我有一个圆圈并将这个圆分成3个扇区(每个120个角)。在圆形区域,有一些已知点(点的坐标已知)。我想知道哪个点属于哪个扇区。输出我想获得个别部门的观点。

我绘制圆圈,划分为扇形并绘制一些点。但我无法确定哪个点属于哪个部门。 我怎么能得到这个?如果有人使用MATLAB有这个过程的任何源代码,它对我有很大帮助。

在这里,我包含了我的源代码

x0 = 2;     % origin x-coordinate
y0 = 1;     % origin y-coordinate
r  = 1;     % radius of circle
n  = 3;     % number of pieces

% predefined points -> [x1,x2,xn;y1,y2,yn]

p = [ 1.5, 2.0, 1.50, 2.4, 1.8, 1.5, 1.7, 2.0, 1.8, 2.5, 2.7, 2.0, 1.3, 1.2, 1.4, 2.2, 1.7, 1.2;
  0.2, 0.8, 1.20, 1.0, 1.3, 0.8, 1.1, 1.4, 0.7, 0.6, 0.5, 0.4, 1.1, 1.3, 1.5, 1.8, 1.5, 1.1];

% calculate circle

theta = -pi:0.01:pi;

cirx = r*cos(theta) + x0;  

ciry = r*sin(theta) + y0;

% initial plot

figure; 
hold on;

axis square;

plot(x0,y0,'or');           % origin

plot(cirx,ciry);            % circle

plot(p(1,:),p(2,:),'go');   % predefined points

% calculate and plot separations

ciro = linspace(-pi,pi,n+1);

for k = 1:(numel(ciro))

ph(k) = plot([x0,x0+r*cos(ciro(k))],[y0,y0+r*sin(ciro(k))]); 

end

1 个答案:

答案 0 :(得分:1)

您应采取的一般方法是使用原点(x0y0将每个笛卡尔(x,y)点转换为它的极坐标等值(rho,theta) )作为中心。然后,您可以使用theta值来确定它属于哪个扇区。

% Compute polar coordinates 
[theta, rho] = cart2pol(p(1,:) - x0, p(2,:) - y0);

% Sector theta values with an extra one at the end for periodicity
sector_thetas = linspace(-pi,pi,n+1);

% Identify which sector it falls into by checking theta against one 
% sector and then the next. Should be greater than one and less than the other
membership = bsxfun(@le, sector_thetas(1:end-1).', theta) & ...
             bsxfun(@gt, sector_thetas(2:end).', theta);

% The result is [nRows x nPoints] and each column will contain a 1 in the row
% corresponding to the sector it belongs to.

% Get the index of which sector it belongs to
% This uses the trick here: http://stackoverflow.com/questions/35950922/finding-the-column-index-for-the-1-in-each-row-of-a-matrix/35951036#35951036
sector = (1:n) * membership;

然后,如果我们绘制不同的部门,我们可以确保事情分组正确

colors = 'grb';

for k = 1:n
    toplot = sector == k;
    p(k) = plot(p(1, toplot), p(2, toplot), ...
                'Color', colors(k), ...
                'Marker', 'o', ...
                'DisplayName', sprintf('Sector %d', k));
end

legend(p);

enter image description here

如果您想知道属于每个组的点索引,您可以执行以下操作。

members = arrayfun(@(x)find(sector == x), 1:n, 'uniform', 0);
celldisp(members)

    members{1} =

        1     2     6     9    12

    members{2} =

        4    10    11

    members{3} =

        3     5     7     8    13    14    15    16    17    18