Skip to content

Commit e921eb1

Browse files
KenoKristofferC
authored andcommitted
Fix #42670 - error in sparsevec outer product with stored zeros (#42671)
The SparseMatrixCSC constructor checks that the passed in buffers have length matching the expected number of non-zeros, but the _outer constructor allocated buffers of the number of structural non-zeros, not actual non-zeros. Fix this by shrinking the buffers once the outer product is fully computed. (cherry picked from commit d885fc2)
1 parent 38c6b79 commit e921eb1

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

stdlib/SparseArrays/src/higherorderfns.jl

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -840,20 +840,28 @@ function _outer(trans::Tf, x, y) where Tf
840840
@inbounds colptrC[1] = 1
841841
@inbounds for jj = 1:nnzy
842842
yval = nzvalsy[jj]
843-
iszero(yval) && continue
843+
if iszero(yval)
844+
nnzC -= nnzx
845+
continue
846+
end
844847
col = rowvaly[jj]
845848
yval = trans(yval)
846849

847850
for ii = 1:nnzx
848851
xval = nzvalsx[ii]
849-
iszero(xval) && continue
852+
if iszero(xval)
853+
nnzC -= 1
854+
continue
855+
end
850856
idx += 1
851857
colptrC[col+1] += 1
852858
rowvalC[idx] = rowvalx[ii]
853859
nzvalsC[idx] = xval * yval
854860
end
855861
end
856862
cumsum!(colptrC, colptrC)
863+
resize!(rowvalC, nnzC)
864+
resize!(nzvalsC, nnzC)
857865

858866
return SparseMatrixCSC(nx, ny, colptrC, rowvalC, nzvalsC)
859867
end

stdlib/SparseArrays/test/higherorderfns.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -726,4 +726,13 @@ end
726726
@test extrema(x; dims=[]) == extrema(y; dims=[])
727727
end
728728

729+
@testset "issue #42670 - error in sparsevec outer product" begin
730+
A = spzeros(Int, 4)
731+
B = copy(A)
732+
C = sparsevec([0 0 1 1 0 0])'
733+
A[2] = 1
734+
A[2] = 0
735+
@test A * C == B * C == spzeros(Int, 4, 6)
736+
end
737+
729738
end # module

0 commit comments

Comments
 (0)