Announcement

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

  • Using vectors/matrices generated by a "for" loop in Mata

    Here everyone,

    In the following loop in Mata, I generate three matrices, which I would like to use subsequently once the loop is executed:

    mata

    for(i=1;i<=3;i++) {

    X = uniform(5,5)
    Yi=i*X


    st_matrix("Yi",Yi)

    Yi

    }

    end

    Then, I would like to use the resulting matrices. However, it seems that the matrices are not stored correctly. I cannot even call them. For instance, if I want just to list one of those, let say, Y2, I get the following message:

    matlist Y2

    Y2 not found
    r(111)

    Does anyone know how to deal with this issue?

    Best regards

    Abel

  • #2
    Abel: You might consider working with associative arrays. -help mf_asarray- .

    Consider the following code:
    Code:
    mata
    m=asarray_create("real",1)
    for (j=1;j<=3;j++) {
    X=uniform(5,5)
    asarray(m,j,X)
    }
    
    
    asarray(m,1)
    asarray(m,2)
    
    end
    That is, you access the matrixes you create by referring to specific elements in the "m" array you've created.

    Comment


    • #3
      Associative arrays are convenient, but tend to consume a lot of memory. An array of pointers to the matrices would be enough.

      Abel wants to send mata matrices back to Stata with names Y1, Y2, Y3
      Mata does not understand macros. Yi in the Mata code is just a variable name and Mata does not understand that the "i" in Yi refers to the "i" in the loop, like it is custamory with loops in Stata.
      This is a recurrent question on this forum and there is an Stata journal article about these issues. It can be found here. One needs to write the name of the new matrix as a string, i.e. as "Y"+strofreal(i).

      Code:
      for(i=1;i<=3;i++) {
      
      X = uniform(5,5)
      Yi=i*X
      
      
      st_matrix("Y"+strofreal(i),Yi)
      
      Yi
      
      }

      Comment


      • #4
        John and Christophe thanks very much for your suggestions and recommendations. They all have been very insightful

        Comment

        Working...
        X