在matlab中选择特定半径内n个点的列表?

时间:2017-07-14 06:01:12

标签: matlab

我有一个这样的轨迹:我们假设每个红色星形标记可以将其坐标广播到绿色圆圈标记,这些标记位于距离其自身位置5个半径范围内。

enter image description here

如何根据以上说明为每个绿色标记选择n个红点列表。提前谢谢。

这是我的代码,我在其中提到了红点和绿色标记的坐标。

 %% Network Setup
anchor_num=1; % Number of anchor node
node_num=20;  % Total nodes
length1=70;   % Area length
anchor_x=0;   % Intial position of anchor x coordinate
anchor_y=0;   % Intial position of anchor y coordinate
anchormove=[];% Anchor trajectory
width=40;    % Area width
r = 30;     
A = zeros(0,2);
B = zeros(0,2);
C = zeros(0,2);
D = zeros(0,2);
north = [ 0 6.9];
east  = [ 6.9 0];
south = [ 0 -6.9];
west  = [-6.9 0];
order = 4;
for n = 1:order
  AA = [B ; north ; A ; east  ; A ; south ; C];
  BB = [A ; east  ; B ; north ; B ; west  ; D];
  CC = [D ; west  ; C ; south ; C ; east  ; A];
  DD = [C ; south ; D ; west  ; D ; north ; B];
  A = AA;
  B = BB;
  C = CC;
  D = DD;
end
% Plot network trajectory
%Mtrix A contains the coordinate of red markers.
A = [0 0; cumsum(A)]
p=plot(A(:,1),A(:,2))
title('Plot of Hilbert trajectory');
set(p,'Color','magenta ','LineWidth',2);
axis([0 100 0 100]);
hold on
% x and y are the coordinates of green markers
x=rand(1,100)*100;
y=rand(1,100)*100;
scatter(x,y)

anchormove(1,:)=A(:,1)'
anchormove(2,:)=A(:,2)'
idx=length(anchormove(1,:));
for i=1:idx-1
    % Plot the moving anchor node
    Ax=anchormove(1,i);
    Ay=anchormove(2,i);
    plot(Ax,Ay,'r*');
% Plot transmission range of the anchor node
    axis([0 100 0 100])
   % hold on
    pause(0.1)
    %hold off
end

2 个答案:

答案 0 :(得分:1)

如果您没有统计数据和机器学习工具箱,您可以手动完成。要查找所有“红色”点(来自您的代码,似乎它们包含在A中),这些点位于特定绿点(Rx(i))的y(i)范围内,你可以使用

w = sqrt(sum((A - [x(i),y(i)]).^2,2)) <= R;

如果你有Matlab&gt; = R2016,否则

w = sqrt(sum((A - repmat([x(i),y(i)],size(A,1),1)).^2,2)) <= R;

然后,w是一个逻辑数组,包含R范围[x(i),y(i)]内所有锚点的逻辑1。您可以使用逻辑索引àlaA(w,:)来检索它们。例如,plot(A(w,1),A(w,2),'ks')将使用不同的标记绘制它们。

如果您需要共同为所有绿点执行此操作,则代码将变为

W = sqrt(sum(abs((reshape(A,size(A,1),1,2) - reshape([x;y]',1,length(x),2)).^2),3)) <= R;

on Matlab&gt; = R2016。现在,W是一个矩阵,其行是红点,列是绿色标记,如果一对在半径R内,则包含逻辑1,否则为0。例如,您可以使用any(W,2)检查红点是否在任何绿色标记的触及范围内。

对于R2016之前的Matlab,您需要使用一些repmat magic修改上述内容:

W = sqrt(sum(abs((repmat(reshape(A,size(A,1),1,2),1,length(x),1) - repmat(reshape([x;y]',1,length(x),2),size(A,1),1,1)).^2),3)) <= R;

答案 1 :(得分:0)

您可以使用rangesearch(X,Y,radius)。它返回一个单元格数组,其中单元格包含每个点X在给定radius内的点Y的索引。由于每个Y附近点的数量可能不同,因此每个单元格的索引数可能会有所不同。

所以在你的情况下:

% turn the two x and y vectors into [x y] column format.
GreenPoints = [x;y].';
% get indexes of the points A for each Green point within 5 distance
idx = rangesearch(A,GreenPoints,5);

或更短:

idx = rangesearch(A,[x;y].',5);