www.gusucode.com > stats 源码程序 matlab案例代码 > stats/SearchForNearestNeighborsOfQueryDataUsingTheMahalanobisDExample.m
%% Search for Nearest Neighbors of Query Data 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 an exhaustive nearest neighbors searcher using the training data. Specify to % use the Mahalanobis distance for finding nearest neighbors later. Mdl = createns(X,'NSMethod','exhaustive','Distance','mahalanobis') %% % |Mdl| is an |ExhaustiveSearcher| model object. By default, the Mahalanobis % metric parameter value is the estimated covariance matrix of the % predictors (columns) in the training data. To display % this value,use |Mdl.DistPatameter|. Mdl.DistParameter %% % Find the indices of the training data (|Mdl.X|) that are the two nearest % neighbors of each point in the query data (|Q|). IdxNN = knnsearch(Mdl,Y,'K',2) %% % Each row of |NN| corresponds to a query data observation. The column % order corresponds to the order of the nearest neighbors with respect to % ascending distance. For example, using the Mahalanobis metric, the second nearest neighbor of |Q(3,:)| is |X(34,:)|.