From 7f310b42d20952e3cc1f26bf66833b7bf9089ead Mon Sep 17 00:00:00 2001 From: Tim Holy Date: Mon, 13 Oct 2025 07:54:08 -0500 Subject: [PATCH] Add working & efficient `fill!(A, 0)` --- src/SparseMatrixCSR.jl | 11 ++++++++--- test/SparseMatrixCSR.jl | 4 ++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/SparseMatrixCSR.jl b/src/SparseMatrixCSR.jl index 66a0df4..d145d09 100644 --- a/src/SparseMatrixCSR.jl +++ b/src/SparseMatrixCSR.jl @@ -37,7 +37,7 @@ struct SparseMatrixCSR{Bi,Tv,Ti} <: AbstractSparseMatrix{Tv,Ti} throw(ArgumentError("$str must be $r, got $k")) m < 0 && throwsz("m",">=0",m) n < 0 && throwsz("n",">=0", n) - length(rowptr) != m+1 && throwsz("lengh(rowptr)",m+1,length(rowptr)) + length(rowptr) != m+1 && throwsz("length(rowptr)",m+1,length(rowptr)) rowptr[end]-Bi != length(nzval) && throwsz("rowptr[end]-Bi",rowptr[m+1]-Bi, length(nzval)) new{Bi,Tv,Ti}(Int(m), Int(n), rowptr, colval, nzval) end @@ -58,14 +58,14 @@ end """ SparseMatrixCSR(a::SparseMatrixCSC} -Build a 1-based `SparseMatrixCSR` from a `SparseMatrixCSC`. +Build a 1-based `SparseMatrixCSR` from a `SparseMatrixCSC`. """ SparseMatrixCSR(a::SparseMatrixCSC) = SparseMatrixCSR(transpose(sparse(transpose(a)))) """ SparseMatrixCSR(a::AbstractMatrix} -Build a 1-based `SparseMatrixCSR` from an `AbstractMatrix`. +Build a 1-based `SparseMatrixCSR` from an `AbstractMatrix`. """ SparseMatrixCSR(a::AbstractMatrix) = SparseMatrixCSR(sparse(a)) @@ -141,6 +141,11 @@ function LinearAlgebra.fillstored!(a::SparseMatrixCSR,v) a end +function Base.fill!(a::SparseMatrixCSR,v) + iszero(v) && return LinearAlgebra.fillstored!(a,v) + invoke(Base.fill!,Tuple{AbstractMatrix,typeof(v)},a,v) +end + function LinearAlgebra.rmul!(a::SparseMatrixCSR,v::Number) rmul!(a.nzval,v) a diff --git a/test/SparseMatrixCSR.jl b/test/SparseMatrixCSR.jl index 47bad8d..69e9709 100644 --- a/test/SparseMatrixCSR.jl +++ b/test/SparseMatrixCSR.jl @@ -118,6 +118,10 @@ function test_csr(Bi,Tv,Ti) mul!(z,CSC,x) @test y ≈ z + @test_throws ArgumentError fill!(CSR2,3.33) + fill!(CSR2, 0) + @test all(iszero, CSR2) + # test constructors @test CSR == SparseMatrixCSR(CSC) @test CSR == SparseMatrixCSR(Matrix(CSC))