Skip to content

Commit 2414ceb

Browse files
committed
Fix -, conj, and conj! for sparse matrices with invalid entries in nzval
1 parent 9732693 commit 2414ceb

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

15051505
# TODO: More appropriate location?
1506-
conj!(A::SparseMatrixCSC) = (@inbounds broadcast!(conj, A.nzval, A.nzval); A)
1507-
(-)(A::SparseMatrixCSC) = SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), map(-, A.nzval))
1506+
function conj!(A::SparseMatrixCSC)
1507+
map!(conj, view(A.nzval, 1:nnz(A)), view(A.nzval, 1:nnz(A)))
1508+
return A
1509+
end
1510+
function (-)(A::SparseMatrixCSC)
1511+
nzval = similar(A.nzval)
1512+
map!(-, view(nzval, 1:nnz(A)), view(A.nzval, 1:nnz(A)))
1513+
return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval)
1514+
end
15081515

15091516
# the rest of real, conj, imag are handled correctly via AbstractArray methods
1510-
conj(A::SparseMatrixCSC{<:Complex}) =
1511-
SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), conj(A.nzval))
1517+
function conj(A::SparseMatrixCSC{<:Complex})
1518+
nzval = similar(A.nzval)
1519+
map!(conj, view(nzval, 1:nnz(A)), view(A.nzval, 1:nnz(A)))
1520+
return SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), nzval)
1521+
end
15121522
imag(A::SparseMatrixCSC{Tv,Ti}) where {Tv<:Real,Ti} = spzeros(Tv, Ti, A.m, A.n)
15131523

15141524
## Binary arithmetic and boolean operators

stdlib/SparseArrays/test/sparse.jl

+12
Original file line numberDiff line numberDiff line change
@@ -2518,4 +2518,16 @@ end
25182518
@test_throws ArgumentError sparse(I1, J1, zero(length(I1)zero(length(I1))))
25192519
end
25202520

2521+
@testset "unary operations on matrices where length(nzval)>nnz" begin
2522+
# this should create a sparse matrix with length(nzval)>nnz
2523+
A = SparseMatrixCSC(Complex{BigInt}[1+im 2+2im]')'[1:1, 2:2]
2524+
# ...ensure it does! If necessary, the test needs to be updated to use
2525+
# another mechanism to create a suitable A.
2526+
@assert length(A.nzval) > nnz(A)
2527+
@test -A == fill(-2-2im, 1, 1)
2528+
@test conj(A) == fill(2-2im, 1, 1)
2529+
conj!(A)
2530+
@test A == fill(2-2im, 1, 1)
2531+
end
2532+
25212533
end # module

0 commit comments

Comments
 (0)