Search code examples
matrixstatalocalr-rownames

Name matrix rows with a loop Stata


I have a matrix with dimensions of 4x2. I would like to name the rows with a loop.

For example. From something like this:

      c1 c2
  r1  0  0
  r2  0  0
  r3  0  0
  r4  0  0

I would like this:

       c1  c2
  _0_3  0   0
  _1_4  0   0
  _2_5  0   0
  _3_6  0   0

This is my code:

mat WALD = J(4, 2, 0)

forval c = 0/3 {
    local i = `c'
    local z = 3 + `c'
    matrix rownames WALD[`c' + 1] = "_`i'_`z'"
}

Solution

  • The syntax is that all row names are assigned at once. So, you need to take that last statement out of the loop.

    mat WALD = J(4, 2, 0)
    
    forval c = 0/3 {
        local z = 3 + `c'
        local names `names' _`c'_`z'
    }
    
    matrix rownames WALD = `names'
    
    mat li WALD 
    
    WALD[4,2]
          c1  c2
    _0_3   0   0
    _1_4   0   0
    _2_5   0   0
    _3_6   0   0
    

    This could be squeezed into shorter but more cryptic code.