Announcement

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

  • How to invert the order of rows in a matrix

    Dear Statalisters

    Apologies in advance for the simplicity of my question. I am sure the is already a forum answering it but I don't seem able to find it.
    For the porposes of data presentation I have a square matrix, lets say M=(A,B\C,D), and I want to manipulate it so that M=(C,D\A,D).

    Code:
    clear
    matrix define M = (1,2,3\4,5,6\7,8,9)
    matrix list M
    Would be very grateful if someone could guide on how to do it or to a forum exploring this topic

    Many thanks!

  • #2
    Dear Filipe
    Accidently, you have chosen the wrong forum (for Mata). You'll get better help at the Stata forum.
    However, the answer here is (if you mean transposing the matrix):

    Code:
    . matrix define M = (1,2,3\4,5,6\7,8,9)
    
    . matrix list M
    
    M[3,3]
        c1  c2  c3
    r1   1   2   3
    r2   4   5   6
    r3   7   8   9
    
    . matrix trpos = M'
    
    . matrix list trpos
    
    trpos[3,3]
        r1  r2  r3
    c1   1   4   7
    c2   2   5   8
    c3   3   6   9
    Kind regards

    nhb

    Comment


    • #3
      Thank you Niels

      Your suggestion does something similar to what I was looking for but not exactly what I want. Sorry if my query wasn't clear.
      I need to change the order of the rows without changing the order of the columns. For example M = (1,2,3\4,5,6\7,8,9) would be transformed to M = (7,8,9\4,5,6\1,2,3)

      Thanks!

      PS: I will make sure next time I am more attentive to the forum where I post queries.

      Comment


      • #4
        Felipe: Here's one solution that uses Mata to do the row reversal
        Code:
        matrix M=(1,2,3)\(4,5,6)\(7,8,9)
        
        matrix list M
        
        mata st_matrix("MR",st_matrix("M")[rows(st_matrix("M"))..1,.])
        
        matrix list MR

        Comment


        • #5
          Also, see the following by KitBaum

          https://www.stata-journal.com/sjpdf....iclenum=pr0026

          Comment


          • #6
            Thank you John Mullahy and Andrew Musau. Both of your suggestion were very helpful and solved my problem.

            Many thanks!

            Comment

            Working...
            X