---
title: BNNS.NearestNeighbors
framework: accelerate
role: symbol
role_heading: Structure
path: accelerate/bnns/nearestneighbors
---

# BNNS.NearestNeighbors

A structure that calculates k-nearest neighbors.

## Declaration

```swift
struct NearestNeighbors
```

## Overview

Overview The following code generates eight 2D data points and loads them into a k-nearest neighbors object with a single call to the append(samples:) function. The code then computes the four nearest neighbors, based on Euclidean distance, to the sample data point at index 7 of the samples data. let samples: [Float] = [     1, 2,   // 0     7, 2,   // 1     3, 4,   // 2     8, 4,   // 3     3, 7,   // 4     7, 7,   // 5     2, 8,   // 6     2, 5    // 7 ] let samplesDescriptor = BNNSNDArrayDescriptor.allocate(     initializingFrom: samples,     shape: .matrixRowMajor(8, 2))

let maximumSampleCount = 8 let dimensionCount = 2 let nearestNeighborCount = 4

let knn = BNNS.NearestNeighbors(     capacity: maximumSampleCount,     dimensionCount: dimensionCount,     neighborCount: nearestNeighborCount,     dataType: .float)

knn.append(samples: samplesDescriptor)

let indices = BNNSNDArrayDescriptor.allocateUninitialized(     scalarType: Int32.self,     shape: .vector(nearestNeighborCount)) let distances = BNNSNDArrayDescriptor.allocateUninitialized(     scalarType: Int32.self,     shape: .vector(nearestNeighborCount))

knn.apply(index: 7,      outputIndices: indices,      outputDistances: distances) On return, the indices array contains the values [7, 2, 4, 6] and the distances array contains the values [0.0, 1.4142135, 2.236068, 3.0].

## Topics

### Creating a k-nearest neighbors object

- [init(capacity:dimensionCount:neighborCount:dataType:)](accelerate/bnns/nearestneighbors/init(capacity:dimensioncount:neighborcount:datatype:).md)

### Appending data points to a k-nearest neighbors object

- [append(samples:)](accelerate/bnns/nearestneighbors/append(samples:).md)

### Calculating k-nearest neighbors

- [apply(index:outputIndices:outputDistances:)](accelerate/bnns/nearestneighbors/apply(index:outputindices:outputdistances:).md)

## See Also

### K-nearest neighbors calculation

- [BNNSNearestNeighbors](accelerate/bnnsnearestneighbors.md)
- [BNNSCreateNearestNeighbors(_:_:_:_:_:)](accelerate/bnnscreatenearestneighbors(_:_:_:_:_:).md)
- [BNNSNearestNeighborsLoad(_:_:_:)](accelerate/bnnsnearestneighborsload(_:_:_:).md)
- [BNNSNearestNeighborsGetInfo(_:_:_:_:)](accelerate/bnnsnearestneighborsgetinfo(_:_:_:_:).md)
- [BNNSDestroyNearestNeighbors(_:)](accelerate/bnnsdestroynearestneighbors(_:).md)
