Sergey
Sergey

Reputation: 1318

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?

Upvotes: 2

Views: 864

Answers (2)

mbauman
mbauman

Reputation: 31342

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

Upvotes: 3

Sergey
Sergey

Reputation: 1318

Seems like there's a function fillband! that fills space between two diagonals with value, but for some reason it's not exported form the module.

Upvotes: 3

Related Questions