Announcement

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

  • a question about matrix subscripting in mata

    I'm going to construct a vector "myvec". Each element of "myvec" will come from either "vecA" or "vecB" according to a the selection vector, "sel":

    Code:
    vecA  = ("a","b","c")
    vecZ  = ("x","y","z")
    p     = (.5,.5)
    
    rseed(1)
    sel = rdiscrete(1,n_pl,(.5,.5)) // 2,1,2
    
    // desired answer: x,b,z
    My current solution to this is very clumsy:

    Code:
    len   = length(vecA)
    myvec = (vecA,vecZ)[(1..len):+len:*(sel:-1)]
    So I wanted to ask if there is some more natural way to do this in Mata. As is, I think I may end up tossing my clumsy code into a function...though it will get messier if/when I want to select from more than two vectors. Any suggestions would be appreciated. Thanks!

    (I'm used to such a thing in R, which has a vectorized version of Mata's cond ? ifyes : ifno as well as a matrix subsetting syntax (vecA \ vecZ)[...] that would do the trick here.)

  • #2
    You can use:
    Code:
    (vecA \ vecZ)[(1..length(vecA) \ sel)]
    which is a bit less clumsy and would work with more than two vectors in a straight forward way. Although I agree with you that it would be nice if the ternary operator (? : ) would work on matrices as well.
    Best,

    Aljar

    Comment


    • #3
      I find your solutions quite elegant allthough I also miss a vectorized version of if or at least a tool like map in Python to make if or other functions vectorized if needed
      Kind regards

      nhb

      Comment


      • #4
        Thanks for the feedback!

        @Aljar: I can't get your code to work with the inputs I have:

        Code:
        ("a","b","c" \ "x","y","z")[(1..3 \ (2,1,2))]
        gives

        Code:
        <istmt>:  3201  vector required
        r(3201);
        I'd be very interested in an approach that extends to more vectors, though, if you could explain.

        Comment


        • #5
          Hi Frank,

          I am pretty sure that I have tried it before I have posted it, but apparently I have mixed things up because I get the same error as you.
          The only thing that I can come up with to solve it is:
          Code:
          mata
          vecA  = ("a","b","c")
          vecZ  = ("x","y","z")
          p     = (.5,.5)
          n_pl = 3
          rseed(1)
          sel = rdiscrete(1,n_pl,(.5,.5)) // 2,1,2
          vecA :* (sel :== 1) + vecZ :* (sel :== 2)
          end
          With a for loop it is easy to extend it to more vectors. I hope this helps.
          Best,

          Aljar

          Comment


          • #6
            Ok, thanks again Aljar!

            Comment

            Working...
            X