Simd
Simd

Reputation: 21254

How to search and manipulate sparse matrices in Julia

I have a large sparse matrix. I would like to do be able to do two things:

  1. Find a row that has only one non-zero value. Let's call its row index idx.
  2. Zero out column idx, found in 1. I would like to do this efficiently as the matrix is large.

I have tried reading https://docs.julialang.org/en/v1/stdlib/SparseArrays/ but I can't see how to do either.

Upvotes: 1

Views: 1423

Answers (1)

Nils Gudat
Nils Gudat

Reputation: 13800

If I understand you correctly this should work:

julia> using SparseArrays

# Dummy data
julia> A = sparse([1, 1, 2, 2, 3, 3], [1, 2, 3, 1, 2, 3], [2, 3, 0, 0, 0, 5])
3×3 SparseMatrixCSC{Int64,Int64} with 6 stored entries:
  [1, 1]  =  2
  [2, 1]  =  0
  [1, 2]  =  3
  [3, 2]  =  0
  [2, 3]  =  0
  [3, 3]  =  5

# Count non-zero elements across rows
julia> using StatsBase

julia> valcounts = countmap(A.rowval[A.nzval .!= 0])
Dict{Int64,Int64} with 2 entries:
  3 => 1
  1 => 2

# Find the row(s) with only one non-zero element
julia> [k for k ∈ keys(valcounts) if valcounts[k] == 1]
1-element Array{Int64,1}:
 3

# Set the non-zero element in the third row to zero
julia> A[3, A[3, :] .> 0] .= 0
1-element view(::SparseMatrixCSC{Int64,Int64}, 3, [3]) with eltype Int64:
 0

julia> A
3×3 SparseMatrixCSC{Int64,Int64} with 6 stored entries:
  [1, 1]  =  2
  [2, 1]  =  0
  [1, 2]  =  3
  [3, 2]  =  0
  [2, 3]  =  0
  [3, 3]  =  0

Upvotes: 4

Related Questions