如何在 Julia 中搜索和操作稀疏矩阵

fom*_*min 2 julia

我有一个很大的稀疏矩阵。我希望能够做两件事:

  1. 查找只有一个非零值的行。我们称其为 row index idx
  2. 清零列idx,在 1 中找到。我想有效地做到这一点,因为矩阵很大。

我曾尝试阅读https://docs.julialang.org/en/v1/stdlib/SparseArrays/,但我也看不到该怎么做。

Nil*_*dat 5

如果我理解正确,这应该有效:

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
Run Code Online (Sandbox Code Playgroud)