diff --git a/stdlib/SparseArrays/src/sparsematrix.jl b/stdlib/SparseArrays/src/sparsematrix.jl index ff288017571d1..81f23f3664e72 100644 --- a/stdlib/SparseArrays/src/sparsematrix.jl +++ b/stdlib/SparseArrays/src/sparsematrix.jl @@ -1558,12 +1558,22 @@ sparse(s::UniformScaling, dims::Dims{2}) = SparseMatrixCSC(s, dims) sparse(s::UniformScaling, m::Integer, n::Integer) = sparse(s, Dims((m, n))) # TODO: More appropriate location? -conj!(A::SparseMatrixCSC) = (@inbounds broadcast!(conj, A.nzval, A.nzval); A) -(-)(A::SparseMatrixCSC) = SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), map(-, A.nzval)) +function conj!(A::SparseMatrixCSC) + map!(conj, nzvalview(A), nzvalview(A)) + return A +end +function (-)(A::SparseMatrixCSC) + nzval = similar(A.nzval) + map!(-, view(nzval, 1:nnz(A)), nzvalview(A)) + return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval) +end # the rest of real, conj, imag are handled correctly via AbstractArray methods -conj(A::SparseMatrixCSC{<:Complex}) = - SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), conj(A.nzval)) +function conj(A::SparseMatrixCSC{<:Complex}) + nzval = similar(A.nzval) + map!(conj, view(nzval, 1:nnz(A)), nzvalview(A)) + return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval) +end imag(A::SparseMatrixCSC{Tv,Ti}) where {Tv<:Real,Ti} = spzeros(Tv, Ti, A.m, A.n) ## Binary arithmetic and boolean operators diff --git a/stdlib/SparseArrays/test/sparse.jl b/stdlib/SparseArrays/test/sparse.jl index 76dd90bc74c48..89fd7a5e66766 100644 --- a/stdlib/SparseArrays/test/sparse.jl +++ b/stdlib/SparseArrays/test/sparse.jl @@ -2313,4 +2313,16 @@ end @test m2.module == SparseArrays end +@testset "unary operations on matrices where length(nzval)>nnz" begin + # this should create a sparse matrix with length(nzval)>nnz + A = SparseMatrixCSC(Complex{BigInt}[1+im 2+2im]')'[1:1, 2:2] + # ...ensure it does! If necessary, the test needs to be updated to use + # another mechanism to create a suitable A. + @assert length(A.nzval) > nnz(A) + @test -A == fill(-2-2im, 1, 1) + @test conj(A) == fill(2-2im, 1, 1) + conj!(A) + @test A == fill(2-2im, 1, 1) +end + end # module