www.gusucode.com > stats 源码程序 matlab案例代码 > stats/SearchForAllNearestNeighborsWithinASpecifiedDistanceExample.m
%% Search for All Nearest Neighbors Within a Specified Distance % Search for all nearest neighbors within a specified distance of a query % point using |rangesearch| on a |KDTreeSearcher| model. %% % Specify |X| and |Y| as samples of 5-dimensional, normally distributed % variables. % Copyright 2015 The MathWorks, Inc. rng(1); % For reproducibility X = randn(100,5); % Training data Y = randn(10,5); % Query data %% % Grow a _K_ d-tree using |X|. Mdl = KDTreeSearcher(X); %% % |Mdl| is a <docid:stats_ug.bsd9y03-1> model. By default, the % software sets the distance metric to the Euclidean distance. You can % change the default distance using the |'Distance'| name-value pair % argument or using dot notation. %% % Find the points in the training data (specifically, the property % |Mdl.X|) that are within a Euclidean distance |1.5| of each point % in the query data (|Y|). [Idx,D] = rangesearch(Mdl,Y,1.5) %% % |Idx| and |D| are cell vectors of numeric row vectors with length equal % to the number of rows of |Y| (|10| in this case). |Idx{j}| is a row % vector containing the row indices of |X| corresponding to all % observations within |1.5| units of observation |Y(j,:)|. |D{j}| contain % their distances. The software orders the indices in |Idx{j}| and % distances in |D{j}| by closest to furthest. %% % To illustrate the meanings |Idx| and |D|, print all row indices of % |Mdl.X| corresponding to those that are within |1.5| units of % observation 7 in |Y|. Also, print their distances. Idx{7} D{7} %% % |Mdl.X(60,:)| is the closest observation in |X| to |Y(7,:)|, and |Mdl.X(30,:)| is % the next closest. |Mdl.X(60,:)| is |1.2620| units away from |Y(7,:)|, and % |Mdl.X(30,:)| is |1.2638| units away. |Mdl.X(60,:)| and |Mdl.X(30,:)| are the only % two observations in |Mdl.X| that are within |1.5| units of |Y(7,:)|.