Skip to content

Commit b8591c6

Browse files
martinholtersKristofferC
authored andcommitted
Fix -, conj, and conj! for sparse matrices with invalid entries in nzval (#31187)
(cherry picked from commit ca92c7b)
1 parent 5449250 commit b8591c6

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

stdlib/SparseArrays/src/sparsematrix.jl

+14-4
Original file line numberDiff line numberDiff line change
@@ -1566,12 +1566,22 @@ sparse(s::UniformScaling, dims::Dims{2}) = SparseMatrixCSC(s, dims)
15661566
sparse(s::UniformScaling, m::Integer, n::Integer) = sparse(s, Dims((m, n)))
15671567

15681568
# TODO: More appropriate location?
1569-
conj!(A::SparseMatrixCSC) = (@inbounds broadcast!(conj, A.nzval, A.nzval); A)
1570-
(-)(A::SparseMatrixCSC) = SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), map(-, A.nzval))
1569+
function conj!(A::SparseMatrixCSC)
1570+
map!(conj, nzvalview(A), nzvalview(A))
1571+
return A
1572+
end
1573+
function (-)(A::SparseMatrixCSC)
1574+
nzval = similar(A.nzval)
1575+
map!(-, view(nzval, 1:nnz(A)), nzvalview(A))
1576+
return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval)
1577+
end
15711578

15721579
# the rest of real, conj, imag are handled correctly via AbstractArray methods
1573-
conj(A::SparseMatrixCSC{<:Complex}) =
1574-
SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), conj(A.nzval))
1580+
function conj(A::SparseMatrixCSC{<:Complex})
1581+
nzval = similar(A.nzval)
1582+
map!(conj, view(nzval, 1:nnz(A)), nzvalview(A))
1583+
return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval)
1584+
end
15751585
imag(A::SparseMatrixCSC{Tv,Ti}) where {Tv<:Real,Ti} = spzeros(Tv, Ti, A.m, A.n)
15761586

15771587
## Binary arithmetic and boolean operators

stdlib/SparseArrays/test/sparse.jl

+12
Original file line numberDiff line numberDiff line change
@@ -2364,4 +2364,16 @@ end
23642364
@test one(A) isa SparseMatrixCSC{Int}
23652365
end
23662366

2367+
@testset "unary operations on matrices where length(nzval)>nnz" begin
2368+
# this should create a sparse matrix with length(nzval)>nnz
2369+
A = SparseMatrixCSC(Complex{BigInt}[1+im 2+2im]')'[1:1, 2:2]
2370+
# ...ensure it does! If necessary, the test needs to be updated to use
2371+
# another mechanism to create a suitable A.
2372+
@assert length(A.nzval) > nnz(A)
2373+
@test -A == fill(-2-2im, 1, 1)
2374+
@test conj(A) == fill(2-2im, 1, 1)
2375+
conj!(A)
2376+
@test A == fill(2-2im, 1, 1)
2377+
end
2378+
23672379
end # module

0 commit comments

Comments
 (0)