如何在Julia中搜索和处理稀疏矩阵

如何在Julia中搜索和处理稀疏矩阵,julia,Julia,我有一个大的稀疏矩阵。我想做的是能够做两件事: 查找只有一个非零值的行。让我们调用它的行索引idx 归零列idx,在1中找到。由于矩阵很大,我希望能有效地完成这项工作 我已经试过阅读,但我也看不出怎么做。如果我理解正确,这应该可以: 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 Spars

我有一个大的稀疏矩阵。我想做的是能够做两件事:

  • 查找只有一个非零值的行。让我们调用它的行索引
    idx
  • 归零列
    idx
    ,在1中找到。由于矩阵很大,我希望能有效地完成这项工作

  • 我已经试过阅读,但我也看不出怎么做。

    如果我理解正确,这应该可以:

    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
    

    我认为这是第3行的零,但我想在本例中是第3列的零。啊,这很公平,读得不够仔细-你可能想在发生零的行和列之间交换。