Replace diagonals in existing spdiagm array

Hi, wondering if there is an equivalent to the MATLAB method spdiags(Bin, d, A), where the diagonals in A are replaced by those in d with the columns of Bin.

As far as I can tell, spdiagsm does not support a method that allows as input an array A to modify.

The context is finite-difference derivative matrices: one can initialize these to satisfy Dirichlet boundary conditions; implementing Periodic boundary conditions then requires only modifying one diagonal of this array.

Appreciate the support!

This won’t be the most efficient, but perhaps you may do something like

julia> S = spdiagm(-1 => [1,2,3,4], 1 => [4,3,2,1], 0=>1:5)
5×5 SparseMatrixCSC{Int64, Int64} with 13 stored entries:
 1  4  ⋅  ⋅  ⋅
 1  2  3  ⋅  ⋅
 ⋅  2  3  2  ⋅
 ⋅  ⋅  3  4  1
 ⋅  ⋅  ⋅  4  5

julia> S[diagind(S)] .= reverse(1:5)
5-element view(reshape(::SparseMatrixCSC{Int64, Int64}, 25), 1:6:25) with eltype Int64:
 5
 4
 3
 2
 1

julia> S
5×5 SparseMatrixCSC{Int64, Int64} with 13 stored entries:
 5  4  ⋅  ⋅  ⋅
 1  4  3  ⋅  ⋅
 ⋅  2  3  2  ⋅
 ⋅  ⋅  3  2  1
 ⋅  ⋅  ⋅  4  1

If you use BandedMatrices, you may use a Band for the indexing.

julia> S = spdiagm(-1 => [1,2,3,4], 1 => [4,3,2,1], 0=>1:5);

julia> S[Band(1)] = fill(2,4);

julia> S
5×5 SparseMatrixCSC{Int64, Int64} with 13 stored entries:
 1  2  ⋅  ⋅  ⋅
 1  2  2  ⋅  ⋅
 ⋅  2  3  2  ⋅
 ⋅  ⋅  3  4  2
 ⋅  ⋅  ⋅  4  5

Then again, perhaps you may want to work with a BandedMatrix directly. You may convert this to a sparse matrix when necessary.

Thanks for the reply, @jishnub. In my case, I need to add content to a new diagonal, so perhaps the best method right now is to simply redefine the sparse array in full.