Announcement

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

  • Drop a matrix row

    Dear Mata users,

    I'm trying to drop a matrix row (or column, the matrix being symmetric), or at least not counting it in the row() function.
    E.g :

    Consider the following matrix
    Code:
    mata
    M=(0,4,0,0\ 4,0,2,0\ 0,2,0,0\ 0,0,0,0)
    r=rows(M)
    r
    The row function counts 4 rows. However the last one is empty.
    I'd like in this case to return "3", i.e. the number of non empty rows.

    How could I do that?
    Best,
    Charlie

  • #2
    Hi Charlie,

    I would use the select() and rowsum() functions. See an attempt below.

    mata:
    M=(0,4,0,0\ 4,0,2,0\ 0,2,0,0\ 0,0,0,0)
    // colvector counting the number of zeros in each row of M
    row_n_zeros=rowsum((M:==J(1,cols(M),0)))
    // select those rows of M which contain at least one non-zero element
    M_select=select(M,row_n_zeros:<cols(M))
    // number of rows of selected matrix
    r=rows(M_select)
    r
    end

    In a more compact form:

    mata:
    M=(0,4,0,0\ 4,0,2,0\ 0,2,0,0\ 0,0,0,0)
    r=rows(select(M,rowsum((M:==J(1,cols(M),0))):<cols (M)))
    r
    end
    Last edited by Szabolcs Lorincz; 11 Apr 2016, 09:21.

    Comment


    • #3
      Thank you very much Szabolcs,
      This is exactly what I was trying to do.

      Thanks for the stepwise description, it makes it clearer for me.

      Charlie,




      Comment


      • #4
        This can be simplified


        Code:
        M=(0,4,0,0\ 4,0,2,0\ 0,2,0,0\ 0,0,0,0)
        r = colsum(rowsum(M):!=0)
        r
        Edit. To select the non-zero rows

        Code:
        non_zero = select(M, rowsum(abs(M)))

        Best
        Daniel
        Last edited by daniel klein; 12 Apr 2016, 01:49.

        Comment


        • #5
          Thanks Daniel, very useful and elegant.

          Edit

          I even went a step further :
          Code:
          mata 
           M=(0,4,0,0\ 4,0,2,0\ 0,2,0,0\ 0,0,0,0)     
           non_zero= select(select(M, rowsum(abs(M))),colsum(abs(M)))  
               
           non_zero   
               
           end
          Because only the first line kept an empty column, and make my matrix no longer symetric.

          Best,
          Charlie
          Last edited by Charlie Joyez; 14 Apr 2016, 09:31.

          Comment

          Working...
          X