Announcement

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

  • selecting elements with varying indices

    hello

    Sorry if this is too elementary - for each row, I want to select a column specified in another column. Wondering if there is a better Mata approach than the follows:

    Code:
    clear * 
    set obs 10
    
    g a1=cond(_n<5,_n,.)
    g a2=runiform(0,1)
    g b1=cond(_n>5,_n,.)
    g b2=runiform(0,1)
    g c1=_n
    
    
    g c2= cond( c1==a1 , a2, cond(c1==b1,b2,.)) //the Stata way of doing it
    
    
    putmata ab =(a* b*) c1
    mata
    index=J(10,1,.)
    c2=J(10,1,.)
    for (i=1; i<=10; i++) {
    if (length(selectindex(ab[i,]:==c1[i]))>0) {
        index[i]=(selectindex(ab[i,]:==c1[i]))
        c2[i,1]=ab[i,index[i,1]+1]
        }
    } 
    end
    Thanks a lot!

  • #2
    Similarly, is there a better way to obtain matrix b below (for each row, select the last non-missing col)?

    Code:
    mata a=(1\2\3),(4\5\.),(7\.\.)
    mata rnm=rownonmissing(a)
    mata b=a[1,rnm[1]]\a[2,rnm[2]]\a[3,rnm[3]]
    Thanks.

    Comment

    Working...
    X