From c6b2afc0c8c54676e2fbbb7e933d7c167776167f Mon Sep 17 00:00:00 2001 From: Milan Bouchet-Valat Date: Thu, 15 Mar 2018 18:44:51 +0100 Subject: [PATCH] Fix findall() on sparse matrices when some stored entries are false (#26182) The number of returned indices needs to be adjusted in that case. --- stdlib/SparseArrays/src/sparsematrix.jl | 6 ++++-- stdlib/SparseArrays/test/sparse.jl | 9 ++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/stdlib/SparseArrays/src/sparsematrix.jl b/stdlib/SparseArrays/src/sparsematrix.jl index ec02d78518289..eb2c624b7fd8c 100644 --- a/stdlib/SparseArrays/src/sparsematrix.jl +++ b/stdlib/SparseArrays/src/sparsematrix.jl @@ -1306,14 +1306,16 @@ function findall(p::Function, S::SparseMatrixCSC) numnz = nnz(S) inds = Vector{CartesianIndex{2}}(undef, numnz) - count = 1 + count = 0 @inbounds for col = 1 : S.n, k = S.colptr[col] : (S.colptr[col+1]-1) if p(S.nzval[k]) - inds[count] = CartesianIndex(S.rowval[k], col) count += 1 + inds[count] = CartesianIndex(S.rowval[k], col) end end + resize!(inds, count) + return inds end findall(p::Base.OccursIn, x::SparseMatrixCSC) = diff --git a/stdlib/SparseArrays/test/sparse.jl b/stdlib/SparseArrays/test/sparse.jl index a85c3c00bc188..7fdca194ac6f3 100644 --- a/stdlib/SparseArrays/test/sparse.jl +++ b/stdlib/SparseArrays/test/sparse.jl @@ -539,9 +539,16 @@ end @test length(K) == length(J) == length(V) == 2 end -@testset "issue described in https://groups.google.com/d/msg/julia-users/Yq4dh8NOWBQ/GU57L90FZ3EJ" begin +@testset "findall" begin + # issue described in https://groups.google.com/d/msg/julia-users/Yq4dh8NOWBQ/GU57L90FZ3EJ A = sparse(I, 5, 5) @test findall(A) == findall(x -> x == true, A) == findall(Array(A)) + # Non-stored entries are true + @test findall(x -> x == false, A) == findall(x -> x == false, Array(A)) + + # Not all stored entries are true + @test findall(sparse([true false])) == [CartesianIndex(1, 1)] + @test findall(x -> x > 1, sparse([1 2])) == [CartesianIndex(1, 2)] end @testset "issue #5824" begin