I have an array (See below) that when it gets passed to the nnz() function; the return value is 15, which is not the number of non zeros but the the array total. Should it not return 7? I am using v1.0.1.
Thanks for responding. However, because I am working with a third party library, I am stuck with the array as you see above. I did try a conversion.
A = sparse(Matrix(myarray))
nnz(A)
7
Correct answer to be sure, but I’d like to better understand why?
typeof(myarray) yields SparseArrays.SparseMatrixCSC
typeof(A) also yields SparseArrays.SparseMatrixCSC
help?> dropzeros!
search: dropzeros! dropzeros
dropzeros!(A::SparseMatrixCSC; trim::Bool = true)
Removes stored numerical zeros from A, optionally trimming resulting excess space from A.rowval and A.nzval when trim is true.
For an out-of-place version, see dropzeros. For algorithmic information, see fkeep!.
Apologies, maybe my response wasn’t clear - the sparse() function simply produces an Array of type SparseArrays.SparseMatrixCSC, equivalent to what you have (as you noticed from calling typeof). I only used it to create a minimum working example.
What I (and the other posters in this thread) have tried to point out is that the nnz function does not do what you think it should do - it returns the number of elements in your sparse matrix which are “filled”, independent of whether you filled them with a zero.
I simply tried to point out that the behaviour you were apparently looking for (if I understand you correctly) is provided by a different function, count(!iszero, A) - this returns the number of all non-zero elements in your matrix. As Kristoffer says above, you can achieve a similar result by calling dropzero on your matrix:
julia> using SparseArrays
julia> A = sparse([1,2,3],[1,2,3],[0,2,0])
3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:
[1, 1] = 0
[2, 2] = 2
[3, 3] = 0
julia> nnz(A)
3
julia> count(!iszero, A)
1
julia> B = dropzeros(A)
3×3 SparseMatrixCSC{Int64,Int64} with 1 stored entry:
[2, 2] = 2
julia> nnz(B)
1