Announcement

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

  • Finding the non-zero values of the matrix

    Hi,

    I wonder if there would be any easy way for finding the non-zero values of a matrix rather than using two loops for inspecting the matrix element by element?

    Regards,
    Eilya.

  • #2
    I don't know if you just want to have the non-zero values or that you want to have the indices of the non zero values. The code below will give the latter, but it can be easily adjusted if you only want to have the values.
    Best,

    Aljar

    Code:
    real matrix selectindexM(real matrix A){
        b = selectindex(colshape(A :!= 0, 1))
        C = cols(A)
        rowels = ceil(b / C)
        colels = b - rowels :* C :+ C
        return((rowels, colels))
    }

    Comment


    • #3
      The selectindex() function is new in Stata 13. If you don't have Stata 13, you can use this function which is like selectindex(), except it looks for elements that are 1 rather than elements that are non-zero:

      Code:
      // given a vector of 0's and 1's, return indices of the 1's, like selectindex() function added in Stata 13
      // if v = 0 (so can't tell if row or col vector), returns rowvector J(1, 0, 0) 
      real vector OneInds(real vector v) {
          real colvector i, t; real matrix w
          pragma unset i; pragma unset w
          maxindex((cols(v)==1? v \ 0 : v, 0), 1, i, w)
          t = rows(i)>length(v)? J(0, 1, 0) : i
          return (cols(v)==1 & rows(v)!=1? t : t')
      }

      Comment

      Working...
      X