Search code examples
juliasparse-matrixfinite-element-analysis

efficiently insert diagonal in sparse matrix in julia


I'm studying EM computational methods on this resource. These methods use a lot of big sparse matrices with only few diagonals set to non-zero. So my question is this: how do I efficiently set a diagonal of the existing matrix in place in julia?


Solution

  • You can just use indexed assignment:

    julia> using SparseArrays, LinearAlgebra
    
    julia> S = spzeros(10,10)
    10×10 SparseMatrixCSC{Float64,Int64} with 0 stored entries
    
    julia> S[diagind(S)] = rand(10); S
    10×10 SparseMatrixCSC{Float64,Int64} with 10 stored entries:
      [1 ,  1]  =  0.2907
      [2 ,  2]  =  0.451863
      [3 ,  3]  =  0.920742
      [4 ,  4]  =  0.0674684
      [5 ,  5]  =  0.587077
      [6 ,  6]  =  0.61916
      [7 ,  7]  =  0.450401
      [8 ,  8]  =  0.596222
      [9 ,  9]  =  0.597324
      [10, 10]  =  0.210721