Announcement

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

  • looping over two lists of the same length, referring to items at the same position

    I have two local macros that are lists of variables. For example, X = A B C D and Y = 1 2 3 4.

    I want a loop that will refer to the same position of each local macro list at the same time.

    I don't want a nested loop like,

    foreach i in X {
    foreach j in Y {
    gen `i'_`j'=0
    }
    }
    which will create 16 variables.


    I want something like,

    foreach i in [X,Y] {
    gen `i'_`j'=0
    }
    which then creates A_1, B_2, C_3, D_4.


    Also, I'd like a general solution to this, because `i' and `j' could be anywhere inside the loop.

    Thank you in advance.

  • #2
    Here's one approach.
    Code:
    // set up sample macros
    local X A B C D
    local Y 1 2 3 4
    // how many words (show check both X and Y and compare)
    local n : word count `X'
    // loop through the pairs of words
    forvalues i=1/`n' {
    local xi : word `i' of `X'
    local yi : word `i' of `Y'
    display " `xi' `yi' "
    }

    Comment


    • #3
      Variations on a theme of Lisowski:

      Code:
       
      // set up sample macros
      local X A B C D
      local Y 1 2 3 4
      
      // how many words (show check both X and Y and compare)
      local n : word count `X'
      
      // loop through the pairs of words
      tokenize "`X'" 
      forvalues i = 1/`n' {
          display " ``i'' `: word `i' of `Y''"
      }

      Comment


      • #4
        thanks

        Comment

        Working...
        X