# Create graph from knn data

**URL:** <https://igraph.discourse.group/t/create-graph-from-knn-data/1508>\
**Category:** Uncategorized\
**Created:** [16 March 2023 10:40 UTC](https://igraph.discourse.group/t/create-graph-from-knn-data/1508 "2023-03-16T10:40:13Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dg.aragones](https://yyz2.discourse-cdn.com/free1/user_avatar/igraph.discourse.group/dg.aragones/32/586_2.png) [@dg.aragones](https://igraph.discourse.group/u/dg.aragones)\
**Post date:** [16 March 2023 10:40 UTC](https://igraph.discourse.group/t/create-graph-from-knn-data/1508/1 "2023-03-16T10:40:13Z")

</div>

Hello everyone,

I want to create a k-nearest neighbors graph from the information of neighbors (edges) and distances (weights). I have created a simple example:

```auto
idx = matrix(c(1,2,5, 2,1,5, 3,4,5, 4,3,5, 5,4,3), 
             nrow=5, ncol=3, byrow=TRUE)

dist = matrix(c(0,0.3,2.6, 0,0.3,2.6, 0,0.2,1.8, 0,0.2,1.6, 0,1.6,1.8), 
            nrow=5, ncol=3, byrow=TRUE)

```

The first matrix contains in each row the neighbors of each vertex from 1 to 5. The second, contains the distances from each vertex to its neigbors (weights).

Does someone know how to create a weighted graph from that knn data?

Thanks in advance for any help!
