How to efficiently update a Sparse Matrix (Diagonal + Sparse) in-place inside a hot loop?

Matt_jl
Tue, 23 Dec 2025 10:10:46 +0000
General Usage

Hi everyone,

I am working on an iterative algorithm where I need to construct and solve a linear system inside a “hot loop”.

Currently, my code allocates a new sparse matrix A at every iteration because of the operation between a Diagonal matrix and a SparseMatrix.

something like:

using LinearAlgebra, SparseArrays,  BenchmarkTools

function mwe(y::Vector{T},  max_iter::Int=10) where T
    m = length(y)

    D = spdiagm(0 => -2.0 * ones(T, m), 1 => ones(T, m-1), -1 => ones(T, m-1))
    AA = D' * D

    # Buffers
    w = ones(T, m)
    tmp_rhs = similar(y)
    result = similar(y)
    residuals = similar(y)

    for _ in 1:max_iter

        A = Diagonal(w) * AA


        tmp_rhs .= w .* y
        result .= A \ tmp_rhs

       # not used in mwe
        residuals .= y .- result
        w .= 1.0 ./ (1.0 .+ abs.(residuals))
    end

    return result
end

Bonus point: is possible to resolve the linear sistem in-place into the results vector ?
How can I do that?

4 posts - 3 participants