www.gusucode.com > stats 源码程序 matlab案例代码 > stats/SearchForNeighborsWithinARadiusUsingTheMahalanobisDistanExample.m

    %% Search for Neighbors Within a Radius Using the Mahalanobis Distance
%%
% Load Fisher's iris data set.

% Copyright 2015 The MathWorks, Inc.

load fisheriris
%%
% Remove five irises randomly from the predictor data to use as a query set. 
rng(1);                     % For reproducibility
n = size(meas,1);           % Sample size
qIdx = randsample(n,5);     % Indices of query data
X = meas(~ismember(1:n,qIdx),:);
Y = meas(qIdx,:);
%%
% Prepare a default exhaustive nearest neighbors searcher.
Mdl = ExhaustiveSearcher(X)
%%
% |Mdl| is an |ExhaustiveSearcher| model.
%%
% Find the indices of the training data (|X|) that are within 0.15 cm of
% each point in the query data (|Y|).  Specify that the distances are with
% respect to the Mahalanobis metric.
r = 1;
Idx = rangesearch(Mdl,Y,r,'Distance','mahalanobis')
Idx{3}
%%
% Each cell of |Idx| corresponds to a query data observation and contains
% in |X| a vector of indices of the neighbors within 0.15cm  of the query
% data. |rangesearch| arranges the indices in ascending order by distance.
% For example, using thre Mahalanobis distance, the second nearest neighbor
% of |Y(3,:)| is |X(34,:)|.