Announcement

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

  • Conditional Element-wise Transformation of a matrix

    Dear Statalisters,

    I am trying to do a conditional transformation of a matrix, Specifically, I want a new matrix B that returns 1/x if x>1 and x if x<1
    I can do the division just fine, but do not know how to make it conditional on values of x

    Code:
    matrix A=(.5, .3\ 2, 5)
    mata: st_matrix("B", 1 :/ st_matrix("A") )
    matrix list B
    My question is how can I get Mata to return 1/x for 2 and 5, but just x for .5 and .3? I have a feeling it may have to do with mm_cond, but I could not figure it out.

    Thanks for your help!

    Michael Howell-Moroney

  • #2
    The mm_cond() function is part of the community-contributed moremata package available from SSC.
    Code:
    . mata:
    ------------------------------------------------- mata (type end to exit) ----------------------
    : A = (.5, .3\ 2, 5)
    
    : A
            1    2
        +-----------+
      1 |  .5   .3  |
      2 |   2    5  |
        +-----------+
    
    : B = mm_cond(A:<1,1:/A,A)
    
    : B
                     1             2
        +-----------------------------+
      1 |            2   3.333333333  |
      2 |            2             5  |
        +-----------------------------+
    
    : end
    ------------------------------------------------------------------------------------------------

    Comment


    • #3
      Thanks William. I can stop banging my head on the keyboard now!

      Cheers

      Comment


      • #4
        Sometimes, it is fun thinking about mathematical solutions:

        Code:
        A:/(A:^(2:*(A:<1)))

        Comment

        Working...
        X