# How to get the row AND column value for SparseMatrixCSC elements?

**URL:** <https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613>\
**Category:** General Usage\
**Created:** [January 26, 2018, 1:51pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613 "2018-01-26T13:51:24Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![abshej](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/abshej/32/3216_2.png) [@abshej](https://discourse.julialang.org/u/abshej)\
**Post date:** [January 26, 2018, 1:51pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/1 "2018-01-26T13:51:24Z")

</div>

```julia
a = sparse(b)
a.rowvals

```

rowvals only gives the indices of the rows and not the column.  
How to get the row and column indices as a pair, the way it is displayed when entire vector is called

---

<div class="post-metadata">

**Author:** ![mauro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mauro3/32/292_2.png) [@mauro3](https://discourse.julialang.org/u/mauro3)\
**Post date:** [January 26, 2018, 2:01pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/2 "2018-01-26T14:01:14Z")

</div>

Have a look at this and the body of the involved functions (use @edit):

```julia
help?> nzrange                                                                                                                                                          
search: nzrange                                                                                                                                                         
                                                                                                                                                                        
  nzrange(A::SparseMatrixCSC, col::Integer)                                                                                                                             
                                                                                                                                                                        
  Return the range of indices to the structural nonzero values of a sparse matrix column. In conjunction with nonzeros and rowvals, this allows for convenient          
  iterating over a sparse matrix :                                                                                                                                      
                                                                                                                                                                        
  A = sparse(I,J,V)                                                                                                                                                     
  rows = rowvals(A)
  vals = nonzeros(A)
  m, n = size(A)
  for i = 1:n
     for j in nzrange(A, i)
        row = rows[j]
        val = vals[j]
        # perform sparse wizardry...
     end
  end

```

---

<div class="post-metadata">

**Author:** ![abshej](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/abshej/32/3216_2.png) [@abshej](https://discourse.julialang.org/u/abshej)\
**Post date:** [January 26, 2018, 2:46pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/3 "2018-01-26T14:46:22Z")

</div>

Yes, I found that later. But I didn’t quite understand how it gives the i,j location pair of the element as is desired.

---

<div class="post-metadata">

**Author:** ![mauro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mauro3/32/292_2.png) [@mauro3](https://discourse.julialang.org/u/mauro3)\
**Post date:** [January 26, 2018, 2:59pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/4 "2018-01-26T14:59:01Z")

</div>

> **[Sparse matrix | Compressed sparse column (CSC or CCS)](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_column_(CSC_or_CCS))**
>
> CSC is similar to CSR except that values are read first by column, a row index is stored for each value, and column pointers are stored. For example, CSC is (val, row\_ind, col\_ptr), where val is an array of the (top-to-bottom, then left-to-right) non-zero values of the matrix; row\_ind is the row indices corresponding to the values; and, col\_ptr is the list of val indexes where each column starts. The name is based on the fact that column index information is compressed relative to the COO format....

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [January 26, 2018, 3:05pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/6 "2018-01-26T15:05:07Z")

</div>

Loop over the columns as `j`, and `nzrange(A,j)` gives you the rows for column `j` which have nonzeros.

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [January 26, 2018, 3:11pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/7 "2018-01-26T15:11:52Z")

</div>

> [@ChrisRackauckas](#):
>
> Loop over the columns as j, and nzrange(A,j) gives you the rows for column j which have nonzeros.

No, it gives you the indices into `A.rowval`, which contains the rows, e.g.

```julia
julia> A = [1 0 0;
            1 8 7;
            2 9 0] |> sparse;

julia> A.rowval[nzrange(A, 2)]
2-element Array{Int64,1}:
 2
 3

julia> A.rowval[nzrange(A, 3)]
1-element Array{Int64,1}:
 2

```

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [January 26, 2018, 3:22pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/8 "2018-01-26T15:22:21Z")

</div>

> [@kristoffer.carlsson](#):
>
> No, it gives you the indices into A.rowval, which contains the rows, e.g.

I never get this right… this can really be improved. I opened an issue to see if not only this can be improved, but also see if it can be standardized beyond `SparseMatrixCSC`:

> <https://github.com/JuliaLang/julia/issues/25760>
>
> It would be nice to have a clearly defined \`AbstractSparseArray \<: AbstractArray…\` with an interface that defines where the non-zero values are, and that way generic looping over sparse arrays can be defined. Special matrix types like \`Tridiagonal\` should fall under \`AbstractSparseArray\` to allow for generic sparse iteration, and then it would make it easier for things like @dlfivefifty 's BandedMatrices.jl to plug into a more generic system of sparsity support.

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [January 26, 2018, 3:30pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/9 "2018-01-26T15:30:02Z")

</div>

> [@ChrisRackauckas](#):
>
> this can really be improved

SparseMatrices are not good to index with Cartesian indices and if you want to apply something to do something to all items, why not use the higher level functions like `map`?.

Working efficiently with sparse matrices will in many cases mean working directly with the internal representation.

---

<div class="post-metadata">

**Author:** ![rveltz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rveltz/32/2707_2.png) [@rveltz](https://discourse.julialang.org/u/rveltz)\
**Post date:** [January 26, 2018, 3:33pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/10 "2018-01-26T15:33:09Z")

</div>

Maybe you can just multiply by the vector `(0,0,...0,1,0,...,0)`

---

<div class="post-metadata">

**Author:** ![abshej](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/abshej/32/3216_2.png) [@abshej](https://discourse.julialang.org/u/abshej)\
**Post date:** [January 26, 2018, 3:44pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/11 "2018-01-26T15:44:11Z")

</div>

Sorry, I don’t understand.

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [January 26, 2018, 3:53pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/12 "2018-01-26T15:53:16Z")

</div>

> [@kristoffer.carlsson](#):
>
> SparseMatrices are not good to index with Cartesian indices and if you want to apply something to do something to all items, why not use the higher level functions like map?.

Who asked to index sparse matrices with a Cartesian? I specifically asked for efficient iterators to avoid looping through non-zero elements with Cartesians. Of course those iterators have be specialized to the internal representation to be efficient, but that’s well within the realm of what’s possible if the iterator could return some indexing type. I am not asking for something to write matrix multiplications with, of course that needs to be really specialized to the sparse array. But I think that the ability to write a loop over the non-zero elements without having to make it a `map` would be helpful in a lot of cases.

---

<div class="post-metadata">

**Author:** ![abshej](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/abshej/32/3216_2.png) [@abshej](https://discourse.julialang.org/u/abshej)\
**Post date:** [January 26, 2018, 3:57pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/13 "2018-01-26T15:57:35Z")

</div>

Agreed. One reason is the growing use of sparse representations in ML. Performing quick iterations is necessary.

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [January 26, 2018, 4:04pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/14 "2018-01-26T16:04:21Z")

</div>

Anyway, the answer to the question in OP is:

```julia
julia> A = sprand(5, 5, 0.2);

julia> I, J, V = findnz(A);

julia> indices = collect(zip(I,J));

julia> indices
6-element Array{Tuple{Int64,Int64},1}:
 (1, 1)
 (2, 1)
 (3, 2)
 (3, 4)
 (1, 5)
 (5, 5)

julia> V
6-element Array{Float64,1}:
 0.0129232
 0.187362
 0.713473
 0.595695
 0.415127
 0.640516

```

---

<div class="post-metadata">

**Author:** ![abshej](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/abshej/32/3216_2.png) [@abshej](https://discourse.julialang.org/u/abshej)\
**Post date:** [January 26, 2018, 4:13pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/15 "2018-01-26T16:13:55Z")

</div>

Yes! That works. Thank you @kristoffer.carlsson!

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [January 26, 2018, 4:20pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/16 "2018-01-26T16:20:59Z")

</div>

And here is an iterator that gives the cartesian indices and the values:

```julia
struct SparseMatrixCSC_StoredValuesIterator{T}
    A::T
end

Base.start(S::SparseMatrixCSC_StoredValuesIterator) = 1, 1

function Base.next(S::SparseMatrixCSC_StoredValuesIterator, state)
    i, col = state
    while i > S.A.colptr[col+1] - 1
        col += 1
    end
    return (S.A.rowval[i], col, S.A.nzval[i]), (i + 1, col)
end

function Base.done(S::SparseMatrixCSC_StoredValuesIterator, state)
    i, col = state
    return i > S.A.colptr[end] - 1
end

stored_indvals(S::SparseMatrixCSC) = SparseMatrixCSC_StoredValuesIterator(S)

```

Used as:

```julia
julia> A = sprand(6, 6, 0.4);

julia> full(A)
6×6 Array{Float64,2}:
 0.0 0.0 0.0 0.056908 0.0 0.0
 0.0 0.328863 0.0 0.0 0.522739 0.0
 0.0 0.0 0.0 0.0 0.559482 0.498087
 0.0 0.0360203 0.0 0.302467 0.0 0.111877
 0.0 0.489175 0.77902 0.117499 0.0 0.0
 0.0 0.513361 0.0 0.801586 0.0 0.0582955

julia> for (i, j, v) in stored_indvals(A)
           println("A[$i, $j] = $v")
       end
A[2, 2] = 0.32886263776211333
A[4, 2] = 0.03602034051160041
A[5, 2] = 0.489174826870322
A[6, 2] = 0.5133613097745331
A[5, 3] = 0.7790200708345987
A[1, 4] = 0.0569080303985654
A[4, 4] = 0.30246686231168973
A[5, 4] = 0.11749932772395755
A[6, 4] = 0.8015857984258852
A[2, 5] = 0.5227388963966788
A[3, 5] = 0.5594820109904008
A[3, 6] = 0.49808711016882445
A[4, 6] = 0.1118766615390987
A[6, 6] = 0.05829550762538971

```

Note, haven’t tested this one properly, it might have some off by one or fail on other edge cases.

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [January 26, 2018, 11:12pm UTC](https://discourse.julialang.org/t/how-to-get-the-row-and-column-value-for-sparsematrixcsc-elements/8613/17 "2018-01-26T23:12:58Z")

</div>

Check out [https://github.com/timholy/ArrayIteration.jl](https://github.com/timholy/ArrayIteration.jl) which has an awesome proof of concept.
