Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Equivalent of count_nonzero()

    Dear, All,

    just wanted to confirm with you whether there exists a built-in function in Mata to calculate the equivalent of python's count_nonzero(), which reports the number (count) of the elements of a matrix that are different from zero.

    No problem implementing this with nested loops. Just looking for a built-in function if available.

    Thank you, Sergiy

  • #2
    Would count0 = sum(A:!=0) work for you?

    Comment


    • #3
      Yes, Mike, thank you very much!
      This is perfect!


      Code:
      mata
      A=1,2,0,0,7 \ 2,0,0,1,0
      sum(A:!=0)
      sum(A[1,.]:!=0)
      sum(A[2,.]:!=0)
      end
      Code:
      . mata
      ------------------------------------------------- mata (type end to exit) ------------------------------------------------------------------------------------------------
      : A=1,2,0,0,7 \ 2,0,0,1,0
      
      : sum(A:!=0)
        5
      
      : sum(A[1,.]:!=0)
        3
      
      : sum(A[2,.]:!=0)
        2
      
      : end

      Comment

      Working...
      X