Skip to content

Commit 0e76dbb

Browse files
committed
added diagonal-sparse multiplication
1 parent 313a04f commit 0e76dbb

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/linalg.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,16 @@ function _A_mul_Bt_or_Bc!(tfun::Function, C::StridedMatrix, A::AbstractMatrix, B
188188
C
189189
end
190190

191+
function *(A::Diagonal, b::AbstractSparseVector)
192+
T = promote_eltype(A, b)
193+
nzind_b = nonzeroinds(b)
194+
nzval_b = nonzeros(b)
195+
if isempty(nzind_b)
196+
return zero(T)
197+
end
198+
return sum(A.diag[nzind_b[idx]] * nzval_b[idx] for idx in eachindex(nzind_b))
199+
end
200+
191201
# Sparse matrix multiplication as described in [Gustavson, 1978]:
192202
# http://dl.acm.org/citation.cfm?id=355796
193203

test/linalg.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,16 @@ end
673673
end
674674
end
675675

676+
@testset "diagonal - sparse vector mutliplication" begin
677+
for _ in 1:10
678+
b = spzeros(10)
679+
b[1:3] .= 1:3
680+
A = Diagonal(randn(10))
681+
@test norm(A * b - A * Vector(b)) <= 10eps()
682+
@test norm(A * b - Array(A) * b) <= 10eps()
683+
end
684+
end
685+
676686
@testset "sparse matrix * BitArray" begin
677687
A = sprand(5,5,0.3)
678688
MA = Array(A)

0 commit comments

Comments
 (0)