Announcement

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

  • Loop and mata

    hello, i need to run the mata function inside a foreach, but when i give the end to mata, i get a break and it doesn't let me run the rest of the loop, does anyone know how i can correct this?


  • #2
    Here are three answers: I guess there are others.

    1. Do you need end at all? Many on-the-fly uses of Mata don't need it at all.

    Here is a silly example:

    Code:
    sysuse auto, clear
    gen wanted = .
    local i = 0
    foreach v in price mpg weight {
    local ++
    mata : work = st_data(., "`v'")
    mata :  st_numscalar("mean", mean(work))
    replace wanted = scalar(mean) in `i'

    2. If the Mata code is complicated, make it into a Mata function.

    3. Include the Mata code in a new Stata command.

    In #2 and #3 the point is that any end statements just are not visible to the loop.

    Comment


    • #3
      If you want
      • a block of Mata code terminated by end
      to run within
      • a Stata block surrounded by braces {} - typically a program, but in fact within any brace-enclosed block of code
      you need to
      • define your Mata code as a Mata function outside the brace-enclosed block
      • call the Mata function within the brace-enclosed block
      Even though your "end" is meant to terminate a Mata block, at the time Stata is parsing the loop, the fact that the "end" belongs to Mata and not to Stata is not recognized, and causes Stata to react incorrectly.

      Comment


      • #4
        could you help me with Dhat_f, I am trying to do the subtraction to find this result, but it appears that the matrix D_f does not exist, however when there is the operation separately, it appears step by step, do you know how I can do this subtraction?

        Click image for larger version

Name:	Imagen de WhatsApp 2023-01-23 a las 14.48.20.jpg
Views:	1
Size:	1.50 MB
ID:	1698363

        Comment


        • #5
          Hi Maria Henao , Please provide a reproducible example.

          Comment


          • #6
            It seems you want to write a mata function like you do above, and instead of creating the loop with the code, make the loop using the function instead. Have you answered this question yet?

            Comment

            Working...
            X