Announcement

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

  • Looping across matrices

    Hi, I cannot find the answer to this and it is maddening.

    I am trying to loop in Mata. I need to loop in Mata because I am creating matrices that are used in a solver. In the following code I am creating the vector firstterm, but I cannot figure out how to loop over the S_pp matrices (from S_pp1-S_pp100), where $models=100.


    mata:
    for (i = 1; i <= $models; i++) {
    for (j = 1; j <= $models; j++) {
    for (k = 1; k <= $models; k++) {
    if (i == j & j == k) {
    firstterm = J($draws, 1, .)
    for (n = 1; n <= $draws; n++) {
    firstterm[n, 1] = sim_B_rand_price_sim[n, 1]^2 * (1 - 2 * sim_shares_sim[i, n]) * sim_shares_sim[i, n] * (1 - sim_shares_sim[i, n]) / $draws
    }
    S_ppi[j, k] = sum(firstterm)
    .......

    The rest of the code is not needed to answer the question. If anyone could help me figure out how to edit S_ppi[j,k] so that the code will loop over the existing matrices S_pp1-S_pp100, I will be eternally grateful.

  • #2
    Scott, to loop thru sequential matrices, a row vector of pointers, helps.

    . help [M-2] pointers


    Code:
    mata:
    
    P = J(1, 3, NULL) <--- row vector of pointers
    
    for (x=1; x<=3; x++) {
    P[x] = &J(2,2,x) <--- storing matrix's pointer address in the row vector
    }
    
    
    for (x=1; x<=3; x++) {
    *P[x] <--- loop to access stored matrix
    }
    
    
    [symmetric]
           1   2
        +---------+
      1 |  1      |
      2 |  1   1  |
        +---------+
    [symmetric]
           1   2
        +---------+
      1 |  2      |
      2 |  2   2  |
        +---------+
    [symmetric]
           1   2
        +---------+
      1 |  3      |
      2 |  3   3  |
        +---------+
    LP

    Comment

    Working...
    X