Skip to content

Commit

Permalink
Don't materialize when adding/subtracting an Array (#456)
Browse files Browse the repository at this point in the history
Don't materialize when adding/subtracting an Array
  • Loading branch information
jishnub authored Oct 16, 2023
1 parent 7add142 commit 3582898
Showing 1 changed file with 48 additions and 4 deletions.
52 changes: 48 additions & 4 deletions src/sparsematrix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2242,10 +2242,54 @@ imag(A::AbstractSparseMatrixCSC{Tv,Ti}) where {Tv<:Real,Ti} = spzeros(Tv, Ti, si
(+)(A::AbstractSparseMatrixCSC, B::AbstractSparseMatrixCSC) = map(+, A, B)
(-)(A::AbstractSparseMatrixCSC, B::AbstractSparseMatrixCSC) = map(-, A, B)

(+)(A::AbstractSparseMatrixCSC, B::Array) = Array(A) + B
(+)(A::Array, B::AbstractSparseMatrixCSC) = A + Array(B)
(-)(A::AbstractSparseMatrixCSC, B::Array) = Array(A) - B
(-)(A::Array, B::AbstractSparseMatrixCSC) = A - Array(B)
function (+)(A::AbstractSparseMatrixCSC, B::Array)
Base.promote_shape(axes(A), axes(B))
C = Ref(zero(eltype(A))) .+ B
rowinds, nzvals = rowvals(A), nonzeros(A)
for j in axes(A,2)
for i in nzrange(A, j)
rowidx = rowinds[i]
C[rowidx,j] = nzvals[i] + B[rowidx,j]
end
end
return C
end
function (+)(A::Array, B::AbstractSparseMatrixCSC)
Base.promote_shape(axes(A), axes(B))
C = A .+ Ref(zero(eltype(B)))
rowinds, nzvals = rowvals(B), nonzeros(B)
for j in axes(B,2)
for i in nzrange(B, j)
rowidx = rowinds[i]
C[rowidx,j] = A[rowidx,j] + nzvals[i]
end
end
return C
end
function (-)(A::AbstractSparseMatrixCSC, B::Array)
Base.promote_shape(axes(A), axes(B))
C = Ref(zero(eltype(A))) .- B
rowinds, nzvals = rowvals(A), nonzeros(A)
for j in axes(A,2)
for i in nzrange(A, j)
rowidx = rowinds[i]
C[rowidx,j] = nzvals[i] - B[rowidx,j]
end
end
return C
end
function (-)(A::Array, B::AbstractSparseMatrixCSC)
Base.promote_shape(axes(A), axes(B))
C = A .- Ref(zero(eltype(B)))
rowinds, nzvals = rowvals(B), nonzeros(B)
for j in axes(B,2)
for i in nzrange(B, j)
rowidx = rowinds[i]
C[rowidx,j] = A[rowidx,j] - nzvals[i]
end
end
return C
end

## full equality
function ==(A1::AbstractSparseMatrixCSC, A2::AbstractSparseMatrixCSC)
Expand Down

0 comments on commit 3582898

Please sign in to comment.