Announcement

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

  • generating a conditional variable in mata without loop

    I wrote a function in mata to generate a variable in such a way that
    the variable has a well defined value conditional on the value of
    a binary variable. So far, I am able to do this by adding a do operator
    inside the function that iterates over each observation. This loop
    is, however, taking a very long time. Is there a way to write my
    conditional statement in a matrix so that I would not need to loop
    over each observation?

    Here is an example.
    Code:
    clear all
    mata
    sampsize=100
    function geny(xx1){
    y=2*xx1
    return(y)
    }
    u=runiform(sampsize,1,0,1)
    Z=u:>0.5
    X=rnormal(sampsize,1,0,1)
    Y=geny(X)
    end
    I want to generate Y for Z=1

    Thank you in advance
    Last edited by Daniel Abebe; 21 Nov 2019, 03:16.

  • #2
    Since your Z is zero-one you have at least two possibilities:
    Code:
    clear all
    clear all
    mata:
        sampsize=100
        function geny(xx1){
        y=2*xx1
        return(y)
        }
        u=runiform(sampsize,1,0,1)
        Z=u:>0.5
        X=rnormal(sampsize,1,0,1)
    end
    mata: select(geny(X), Z)    //1: select values, disregard positions
    mata: geny(X) :/ Z            //2: select values, keep positions
    Last edited by Niels Henrik Bruun; 21 Nov 2019, 05:58. Reason: better example
    Kind regards

    nhb

    Comment


    • #3
      Thank you Niels. This is an easy solution.

      Comment

      Working...
      X