aboutsummaryrefslogtreecommitdiff
path: root/knn.cpp
blob: 579a76fc308bc10f8fe3d6b352a8f16086de7c23 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "mp.h"

void mp::knn(const arma::mat &dmat, arma::uword i, arma::uword k, arma::uvec &nn, arma::vec &dist)
{
    arma::uword n = dist.n_rows;
    double dmax = arma::datum::inf;
    nn.fill(i);
    dist.fill(dmax);
    if (k > n) {
        return;
    }

    const arma::vec &dvec = dmat.col(i);
    for (arma::uword j = 0; j < n; j++) {
        if (j == i || dvec[j] > dmax) {
            continue;
        }

        arma::uword l;
        for (l = 0; dist[l] < dvec[j] && l < k; l++);
        for (arma::uword m = k - 1; m > l; m--) {
            nn[m]   = nn[m - 1];
            dist[m] = dist[m - 1];
        }

        nn[l] = j;
        dist[l] = dvec[j];
        dmax = dist[k - 1];
    }
}