Announcement

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

  • How to pass the matrix arguments to the mata function in the foreach loop?

    Dear stata users:

    I always enjoy looking this forum and learn a lots!
    Let me ask the question I have today.

    I have several matrices from years 2003-2016 named as:
    W_2003, X_2003, …, W_2016, X_2016.
    “W_”s are spatial weight matrices and matrices “X_” include variables related to the place.
    I would like to make products WX for each year.
    Following is the mock example of my code:

    /*** mata function ***/
    mata
    void wx(string matrix A, string matrix B) {
    A_mat = st_matrix(“A”)
    B_mat = st_matrix(“B”)
    AB_mat = A_mat*B_mat
    st_matrix("AB_mat", AB_mat)
    }
    end
    /*** stata session****/
    /* matrices W_2003, X_2003, … are already defined as “matrix” in the stata */
    forvalues Y=2003/2016 {
    mata: wx(“W_`Y’”, “X_`Y’”)
    }

    However, this code did not work and following errors/notes appeared:

    note: argument A unused
    note: argument B unused

    I suppose I probably have problems of passing the matrices to my Mata function, wx.
    Although I know there are several similar questions had already been posted,
    I couldn’t find the cases using matrices for arguments as far as I know.
    Could anyone suggest remedies to deal with the problem?

    Thanks in advance.

    Kazuto


  • #2
    Maybe you should consider a thrid argument for the name of the new matrix. I guess you want to keep the results of the products.
    You pass "A" instead of A, which triggers the message since the matrix A is not used during the program. Moreover the Stata matrices A and B do not exist which will trigger an error when you run your program.
    The argument you pass to st_matrix is a string scalar. In the first argument it should be A, which is a string scalar (= "W_2003" for example) and not "A".

    Code:
    mata
    void wx(string scalar A, string scalar B) {
    A_mat = st_matrix(A) B_mat = st_matrix(B) AB_mat = A_mat*B_mat st_matrix("AB_mat", AB_mat)
    } end /*** stata session****/ /* matrices W_2003, X_2003, … are already defined as “matrix” in the stata */ forvalues Y=2003/2016 {
    mata: wx(“W_`Y’”, “X_`Y’”)
    }

    Comment


    • #3
      Dear Christophe
      Thanks so much! I misunderstood the way to use "string scalar".
      I could run the code successfully (I added a line to save the calculated matrix as the name with year).
      Code:
       
        mata void wx(string scalar A, string scalar B) {
      A_mat = st_matrix(A) B_mat = st_matrix(B) AB_mat = A_mat*B_mat st_matrix("AB_mat", AB_mat)
      } end /*** stata session****/ /* matrices W_2003, X_2003, … are already defined as “matrix” in the stata */ forvalues Y=2003/2016 {
      mata: wx(“W_`Y’”, “X_`Y’”) matrix AB_mat_`Y' = AB_mat
      }
      Thanks again!

      Comment

      Working...
      X