Announcement

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

  • Convert all elements of a matrix into respective inverse values

    Hi everyone,

    I am having a problem with converting all elements of a matrix to their respective inverse values (NOT the inverse of a matrix). For example, I want element a to become 1/a, element b to become 1/b..... In my example below, the matrix is 8x8. I want to convert all 64 (8*8) elements to their respective inverse values (1/....), so that I can have a new matrix. My real matrix is 63x63 (which is too big for command dataex). I really appreciate your help. Thank you so much!


    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input double p01 int(p02 p04) double(p06 p08) int(p10 p11 p12)
      0 281 269 155 128 287 436 384
    284   0 249 252 154 199 427 303
    277 228   0 114 240 444 721 570
    164 252 114   0 126 330 553 426
    130 154 240 126   0 204 424 310
    289 199 518 330 204   0 303 101
    437 427 722 590 424 301   0 200
    386 303 539 426 310 101 202   0
    end



  • #2
    It is not clear to me if by "matrix" you mean just the array of data you presented, or a Stata matrix, or a matrix within the Mata environment.

    For the first of these options,
    Code:
    . foreach v of varlist * {
      2.     quietly replace `v' = 1/`v'
      3. }
    
    . list, clean noobs
    
              p01       p02       p04         p06         p08       p10       p11       p12  
                .   .003559   .003717   .00645161    .0078125   .003484   .002294   .002604  
        .00352113         .   .004016   .00396825   .00649351   .005025   .002342     .0033  
        .00361011   .004386         .   .00877193   .00416667   .002252   .001387   .001754  
        .00609756   .003968   .008772           .   .00793651    .00303   .001808   .002347  
        .00769231   .006494   .004167   .00793651           .   .004902   .002358   .003226  
        .00346021   .005025   .001931    .0030303   .00490196         .     .0033   .009901  
        .00228833   .002342   .001385   .00169492   .00235849   .003322         .      .005  
        .00259067     .0033   .001855   .00234742   .00322581   .009901    .00495         .  
    
    . 
    ​​​​​​​

    Comment


    • #3
      Thank you so much for your reply, William. I really appreciate.

      Comment


      • #4
        See also this FAQ here:
        https://www.stata.com/support/faqs/d...s-on-matrices/

        Comment


        • #5
          Thank you @Joro Kolev!

          Comment

          Working...
          X