Nnz function appears not to be working

Can anyone explain this?

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

My array as displayed by Jupyter:
3×5 SparseArrays.SparseMatrixCSC{Any,Int64} with 15 stored entries:
[1, 1] = 4
[2, 1] = 0
[3, 1] = 3
[1, 2] = 2
[2, 2] = 0
[3, 2] = 2
[1, 3] = 4
[2, 3] = 0
[3, 3] = 1
[1, 4] = 0
[2, 4] = 0
[3, 4] = 0
[1, 5] = 0
[2, 5] = 0
[3, 5] = 1

I think you want:

``````A = sparse([1, 2, 3], [1, 2, 3], [0, 2, 0])
nnz(A)  # returns 3 (stored elements)
count(!iszero, A) # returns 1 (two of the stored elements are zero
``````

Have a look at the documentation here.

The documentation for `SparseArrays.nnz` says:

Returns the number of stored (filled) elements in a sparse array.

So the zeros that are explicitly stored in the `SparseMatrixCSC` are counted as well.

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

Why the difference?

You can also use `dropzeros!`

``````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
``````