Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added diagonal-sparse multiplication #564

Merged
merged 6 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,22 @@ function _A_mul_Bt_or_Bc!(tfun::Function, C::StridedMatrix, A::AbstractMatrix, B
C
end

function *(A::Diagonal, b::AbstractSparseVector)
if size(A, 2) != length(b)
throw(
DimensionMismatch("The dimension of the matrix A $(size(A)) and of the vector b $(length(b))")
matbesancon marked this conversation as resolved.
Show resolved Hide resolved
)
end
T = promote_eltype(A, b)
res = similar(b, T)
nzind_b = nonzeroinds(b)
nzval_b = nonzeros(b)
for idx in eachindex(nzind_b)
res[nzind_b[idx]] = A.diag[nzind_b[idx]] * nzval_b[idx]
matbesancon marked this conversation as resolved.
Show resolved Hide resolved
end
return res
end

# Sparse matrix multiplication as described in [Gustavson, 1978]:
# http://dl.acm.org/citation.cfm?id=355796

Expand Down
15 changes: 15 additions & 0 deletions test/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,21 @@ end
end
end

@testset "diagonal - sparse vector mutliplication" begin
for _ in 1:10
b = spzeros(10)
b[1:3] .= 1:3
A = Diagonal(randn(10))
@test norm(A * b - A * Vector(b)) <= 10eps()
@test norm(A * b - Array(A) * b) <= 10eps()
Ac = Diagonal(randn(Complex{Float64}, 10))
@test norm(Ac * b - Ac * Vector(b)) <= 10eps()
@test norm(Ac * b - Array(Ac) * b) <= 10eps()
@test_throws DimensionMismatch A * [b; 1]
@test_throws DimensionMismatch A * b[1:end-1]
end
end

@testset "sparse matrix * BitArray" begin
A = sprand(5,5,0.3)
MA = Array(A)
Expand Down
Loading