Skip to content

Commit 186ec10

Browse files
martinholtersKristofferC
authored andcommitted
Fix -, conj, and conj! for sparse matrices with invalid entries in nzval (#31187)
1 parent 4f4384a commit 186ec10

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
@@ -1558,12 +1558,22 @@ sparse(s::UniformScaling, dims::Dims{2}) = SparseMatrixCSC(s, dims)
15581558
sparse(s::UniformScaling, m::Integer, n::Integer) = sparse(s, Dims((m, n)))
15591559

15601560
# TODO: More appropriate location?
1561-
conj!(A::SparseMatrixCSC) = (@inbounds broadcast!(conj, A.nzval, A.nzval); A)
1562-
(-)(A::SparseMatrixCSC) = SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), map(-, A.nzval))
1561+
function conj!(A::SparseMatrixCSC)
1562+
map!(conj, nzvalview(A), nzvalview(A))
1563+
return A
1564+
end
1565+
function (-)(A::SparseMatrixCSC)
1566+
nzval = similar(A.nzval)
1567+
map!(-, view(nzval, 1:nnz(A)), nzvalview(A))
1568+
return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval)
1569+
end
15631570

15641571
# the rest of real, conj, imag are handled correctly via AbstractArray methods
1565-
conj(A::SparseMatrixCSC{<:Complex}) =
1566-
SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), conj(A.nzval))
1572+
function conj(A::SparseMatrixCSC{<:Complex})
1573+
nzval = similar(A.nzval)
1574+
map!(conj, view(nzval, 1:nnz(A)), nzvalview(A))
1575+
return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval)
1576+
end
15671577
imag(A::SparseMatrixCSC{Tv,Ti}) where {Tv<:Real,Ti} = spzeros(Tv, Ti, A.m, A.n)
15681578

15691579
## Binary arithmetic and boolean operators

stdlib/SparseArrays/test/sparse.jl

+12
Original file line numberDiff line numberDiff line change
@@ -2313,4 +2313,16 @@ end
23132313
@test m2.module == SparseArrays
23142314
end
23152315

2316+
@testset "unary operations on matrices where length(nzval)>nnz" begin
2317+
# this should create a sparse matrix with length(nzval)>nnz
2318+
A = SparseMatrixCSC(Complex{BigInt}[1+im 2+2im]')'[1:1, 2:2]
2319+
# ...ensure it does! If necessary, the test needs to be updated to use
2320+
# another mechanism to create a suitable A.
2321+
@assert length(A.nzval) > nnz(A)
2322+
@test -A == fill(-2-2im, 1, 1)
2323+
@test conj(A) == fill(2-2im, 1, 1)
2324+
conj!(A)
2325+
@test A == fill(2-2im, 1, 1)
2326+
end
2327+
23162328
end # module

0 commit comments

Comments
 (0)