Announcement

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

  • pointer yields different results inside and outside loop

    Dear Statalist,
    Could any of you help me understand why a pointer yields different results when I call it from inside a loop than from outside the loop? When I call it inside the loop, it seems to be working fine, but when I call it outside the loop, no matter which part of the pointer I am referring to, it always yields the same result. Please see the example below.

    Code:
    mata:
    
    T = "this is the first line" \ 
    "this would be the second line" \ 
    "final line"
    
    PK = J(1, rows(T), NULL)  
    ngram = 3
    
    for (i =1; i <= rows(T); i++) { 
        for (j =1 ; j<= strlen(T[i,1]); j++) {
            if (j == 1) key = substr(T[i,1], j, ngram)
            else        key = key \ substr(T[i,1], j, ngram)
        }
        PK[i] = &(key)
        printf("Observation %2.0f\n", i)
        (*PK[i]) , key
    }
    (*PK[1])
    (*PK[2])
    (*PK[3])
    end

    As you see, outside the loop (*PK[1]), (*PK[2]), and (*PK[3]) gives me always the same result. Do you know what am I doing wrong? I need to create a couple of pointers in a loop and then use them in a different part of my code.
    Thank you so much.
    Pablo.
    Best,
    Pablo Bonilla

  • #2
    Pablo Bonilla Once you have linked PK[i] to the variable key, changing the content of key will change the content of all the pointers pointing to this variable. The result will be that all the elements of PK point to the same thing, the last evaluation of key. The trick is to point to the evaluation of an expression instead of a variable, here PK[i] = &substr(T[i,1], j, ngram). It is stored in memory and never used again.

    Code:
    mata:
    
    T = "this is the first line" \
    "this would be the second line" \
    "final line"
    
    PK = J(1, rows(T), NULL)  
    ngram = 3
    
    for (i =1; i <= rows(T); i++) {
        for (j =1 ; j<= strlen(T[i,1]); j++) {
            if (j == 1) PK[i] = &substr(T[i,1], j, ngram) // <-- new
            else        (*PK[i]) = (*PK[i])\ substr(T[i,1], j, ngram) // <-- new : change the content of (*PK[i])
            // *PK[i]
        }
        //PK[i] = &(key)
        printf("Observation %2.0f\n", i)
        (*PK[i]) //, key
    }
    (*PK[1])
    (*PK[2])
    (*PK[3])
    end

    Comment


    • #3
      Christophe Kolodziejczyk Thank you so much for your answer. It works beautifully now. Great explanation.
      Best,
      Pablo Bonilla

      Comment

      Working...
      X