How many fillable elements in an AbstractMatrix?

It seems like it should be possible to count the number of “fillable” entries in a matrix, but I can’t work out how to do so for any AbstractMatrix.

What I want:

Some function foo that returns:

  • nnz(A) when A is SparseMatrixCSC.
  • length(A.diag)) if A is Diagonal.
  • prod(size(A)) if A is a Matrix.

I still want to count zeros as long as they are structural zeros, i.e. actually stored somewhere. So I should get :

foo(Diagonal(zeros(3))) == 3
foo(sparse(Diagonal(zeros(3)))) == 0
foo(zeros(3,3)) == 9

Does such a thing exist already?

Nothing like this exists. There aren’t many situations where this is a useful quantity to know. You’ll have to define it yourself for your types of interest if you really need it.

It’s tricky because you’d think that you could do things like
foo(x::LowerTriangular) = div(size(x,1)^2 + size(x,1), 2),
but what about LowerTriangular{T,<:Diagonal}? What about LowerTriangular{T, SparseMatrixCSC{T,Int}} and LowerTriangular{T, Diagonal{T, SparseVector{T,Int}}}? How about UpperTriangular{T, UnitLowerTriangular{T, Matrix{T}}}? And it gets even harder when you start looking at SubArray (ie, view) wrappers. This question is staggeringly complicated when you consider nested types like these.

Yes, I see what you mean and it is not obvious at all what should be expected in some cases. Many thanks.

BTW, for this you can just use length(A), that returns the total number of elements.