Announcement

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

  • Counting elements in a matrix that meet a certain condition

    I have converted the results from an estimation command to a matrix of size 100 x 1 (e.g. mat A= e(W_weights)). I am looking to count the number of elements in that column that are not equal to zero (and save that number in a local). Is there a way to do that?

  • #2
    Code:
    local wanted = 0
    forvalues i = 1/100 {
        local wanted = `wanted' + (A[`i', 1] != 0)
    }
    display `wanted'
    Last edited by Clyde Schechter; 05 Dec 2024, 22:22.

    Comment


    • #3
      If the number of observations is at least 100, you could do this

      Code:
      gen Amat = A[_n, 1] 
      count if Amat != 0 in 1/100
      There is also svmat -- but I could have typed out the above in the time that I had re-discovered the syntax of svmat, which I have not used much since Mata was introduced.

      And now that Mata has been mentioned

      Code:
      mata : sum(st_matrix("A") :!= 0)
      Zero-line solutions would be of interest too.

      Comment

      Working...
      X