From de7b264e4c99ade9bb4906d3ff6b6bc06c239b92 Mon Sep 17 00:00:00 2001 From: Erik Schnetter Date: Mon, 20 Apr 2020 11:26:26 -0400 Subject: [PATCH] SparseArrays: Allow division by diagonal matrices --- stdlib/SparseArrays/src/linalg.jl | 8 ++++++++ stdlib/SparseArrays/test/sparse.jl | 2 ++ 2 files changed, 10 insertions(+) diff --git a/stdlib/SparseArrays/src/linalg.jl b/stdlib/SparseArrays/src/linalg.jl index 070ab01fb0ff7..6b41431db7e78 100644 --- a/stdlib/SparseArrays/src/linalg.jl +++ b/stdlib/SparseArrays/src/linalg.jl @@ -156,6 +156,14 @@ function (*)(A::AbstractSparseMatrixCSC, D::Diagonal) T = Base.promote_op(*, eltype(D), eltype(A)) mul!(LinearAlgebra.copy_oftype(A, T), A, D) end +function (\)(D::Diagonal, A::AbstractSparseMatrixCSC) + T = Base.promote_op(\, eltype(D), eltype(A)) + ldiv!(D, LinearAlgebra.copy_oftype(A, T)) +end +function (/)(A::AbstractSparseMatrixCSC, D::Diagonal) + T = Base.promote_op(/, eltype(A), eltype(D)) + rdiv!(LinearAlgebra.copy_oftype(A, T), D) +end # Sparse matrix multiplication as described in [Gustavson, 1978]: # http://dl.acm.org/citation.cfm?id=355796 diff --git a/stdlib/SparseArrays/test/sparse.jl b/stdlib/SparseArrays/test/sparse.jl index 9449895f16b66..914753e1958c5 100644 --- a/stdlib/SparseArrays/test/sparse.jl +++ b/stdlib/SparseArrays/test/sparse.jl @@ -519,6 +519,7 @@ dA = Array(sA) @test lmul!(Diagonal(bi), copy(dA)) ≈ ldiv!(Diagonal(b), copy(sA)) @test lmul!(Diagonal(bi), copy(dA)) ≈ ldiv!(transpose(Diagonal(b)), copy(sA)) @test lmul!(Diagonal(conj(bi)), copy(dA)) ≈ ldiv!(adjoint(Diagonal(b)), copy(sA)) + @test Diagonal(b) \ copy(sA) == ldiv!(Diagonal(b), copy(sA)) @test_throws DimensionMismatch ldiv!(Diagonal(fill(1., length(b)+1)), copy(sA)) @test_throws LinearAlgebra.SingularException ldiv!(Diagonal(zeros(length(b))), copy(sA)) @@ -527,6 +528,7 @@ dA = Array(sA) @test rmul!(copy(dAt), Diagonal(bi)) ≈ rdiv!(copy(sAt), Diagonal(b)) @test rmul!(copy(dAt), Diagonal(bi)) ≈ rdiv!(copy(sAt), transpose(Diagonal(b))) @test rmul!(copy(dAt), Diagonal(conj(bi))) ≈ rdiv!(copy(sAt), adjoint(Diagonal(b))) + @test copy(sAt) / Diagonal(b) == rdiv!(copy(dAt), Diagonal(b)) @test_throws DimensionMismatch rdiv!(copy(sAt), Diagonal(fill(1., length(b)+1))) @test_throws LinearAlgebra.SingularException rdiv!(copy(sAt), Diagonal(zeros(length(b)))) end