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

    %% Search for Nearest Neighbors of Query Data Using the Minkowski 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,:);
%%
% Grow a four-dimensional _K_ d-tree using the training data.  Specify to use the Minkowski
% distance for finding nearest neighbors later.
Mdl = KDTreeSearcher(X,'Distance','minkowski')
%%
% |Mdl| is a |KDTreeSearcher| model object.  By default, the Minkowski distance
% exponent is |2|.
%%
% Find the indices of the training data (|X|) that are the two nearest neighbors of each point in
% the query data (|Y|).
Idx = knnsearch(Mdl,Y,'K',2)
%%
% Each row of |Idx| corresponds to a query data observation, and the column
% order corresponds to the order of the nearest neighbors, with respect to
% ascending distance.  For example, using the Minkowski distance, the
% second nearest neighbor of |Y(3,:)| is |X(12,:)|.