# Graph from Sparse Matrix

**URL:** <https://discourse.julialang.org/t/graph-from-sparse-matrix/70894>\
**Category:** Graphs\
**Tags:** sparse, graphs\
**Created:** [November 3, 2021, 6:02pm UTC](https://discourse.julialang.org/t/graph-from-sparse-matrix/70894 "2021-11-03T18:02:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rachithaiyappa](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rachithaiyappa/32/22206_2.png) [@rachithaiyappa](https://discourse.julialang.org/u/rachithaiyappa)\
**Post date:** [November 3, 2021, 6:02pm UTC](https://discourse.julialang.org/t/graph-from-sparse-matrix/70894/1 "2021-11-03T18:02:55Z")

</div>

How can I generate a Graph from a SparseMatrixCSC and then convert it into an undirected Light Graph?

---

<div class="post-metadata">

**Author:** ![mthelm85](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mthelm85/32/224164_2.png) [@mthelm85](https://discourse.julialang.org/u/mthelm85)\
**Post date:** [November 3, 2021, 6:20pm UTC](https://discourse.julialang.org/t/graph-from-sparse-matrix/70894/2 "2021-11-03T18:20:45Z")

</div>

You might want to post a MWE because it’s not clear what problem you’re having.

```julia
using LightGraphs
using SparseArrays

julia> X = sprand(Bool, 10, 10, 0.1)
10×10 SparseMatrixCSC{Bool, Int64} with 12 stored entries:
 ⋅ 1 1 ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅
 1 ⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ 1 ⋅ 1 1 ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅ 1
 ⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅

julia> A = X'*X
10×10 SparseMatrixCSC{Int64, Int64} with 24 stored entries:
 2 ⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
 ⋅ 1 1 ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅
 1 1 3 ⋅ 1 1 ⋅ ⋅ 1 ⋅
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ 1 ⋅ 2 1 ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ 1 ⋅ 1 1 ⋅ ⋅ ⋅ ⋅
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅ 1
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
 ⋅ 1 1 ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅
 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅ 1

julia> Graph(A)
{10, 16} undirected simple Int64 graph

```

---

<div class="post-metadata">

**Author:** ![rachithaiyappa](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rachithaiyappa/32/22206_2.png) [@rachithaiyappa](https://discourse.julialang.org/u/rachithaiyappa)\
**Post date:** [November 3, 2021, 6:39pm UTC](https://discourse.julialang.org/t/graph-from-sparse-matrix/70894/3 "2021-11-03T18:39:11Z")

</div>

This helps. Thanks. But I think A = (X’+X)/2 + (X-X’)/2 (not A = X’\*X) ,where (X’+X)/2 is a symmetric matrix. However, the entries of (X’+X)/2 are no longer just 1’s…

What I was trying to do is (probably) a basic task of creating a LightGraph from a sparse matrix (I don’t care about the weight of edges or the directionality of edges) which have entries 1 and 0. Is there a functionality in LightGraph that can do this directly instead of us having to symmetrize the matrix?
