/** Computes the mean across all vectors in the input set of vectors */ static Vector average(List<Vector> ps) { int numVectors = ps.size(); Vector out = new Vector(ps.get(0).elements()); // start from i = 1 since we already copied index 0 above for (int i = 1; i < numVectors; i++) { out.addInPlace(ps.get(i)); } return out.divide(numVectors); }
/** Computes the vector to which the input vector is closest using squared distance */ static int closestPoint(Vector p, List<Vector> centers) { int bestIndex = 0; double closest = Double.POSITIVE_INFINITY; for (int i = 0; i < centers.size(); i++) { double tempDist = p.squaredDist(centers.get(i)); if (tempDist < closest) { closest = tempDist; bestIndex = i; } } return bestIndex; }