Announcement

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

  • Accessing locals in loops

    Hello. I would like to access a number of locals in mata using a for loop and ideally create an equal number of objects with the values. The following code does not work but it gives an idea of what i am trying to do:

    Code:
    local foo1 = 1
    local foo2 = 2
    local foo3 = 3
    
    for(i=1; i<=3; i++) {
        foomata[i] = st_local("foo`i'")
    }

  • #2
    Code:
    for (i=1; i<=3; i++) {
        local_name = "foo" +  strofreal(i)
        foomata[i] = st_local(local_name)
    }
    (Untested)

    Comment


    • #3
      It gives an error: 3201 vector required

      Comment


      • #4
        Well, of course you need to define the vector beforehand—I was addressing only the local macro problem in the loop, which was what I though you we're asking about.

        Here:

        .ÿversionÿ14.2

        .ÿ
        .ÿclearÿ*

        .ÿsetÿmoreÿoff

        .ÿ
        .ÿlocalÿfoo1ÿ=ÿ1

        .ÿlocalÿfoo2ÿ=ÿ2

        .ÿlocalÿfoo3ÿ=ÿ3

        .ÿ
        .ÿlocalÿlinesizeÿ`c(linesize)'

        .ÿsetÿlinesizeÿ80

        .ÿ
        .ÿmata:
        -------------------------------------------------ÿmataÿ(typeÿendÿtoÿexit)ÿ------
        :ÿ
        :ÿFooÿ=ÿJ(1,ÿ3,ÿ"")

        :ÿ
        :ÿforÿ(i=1;ÿi<=3;ÿi++)ÿ{
        >ÿÿÿÿÿlocal_nameÿ=ÿ"foo"ÿ+ÿÿstrofreal(i)
        >ÿÿÿÿÿFoo[i]ÿ=ÿst_local(local_name)
        >ÿ}

        :ÿ
        :ÿFoo
        ÿÿÿÿÿÿÿ1ÿÿÿ2ÿÿÿ3
        ÿÿÿÿ+-------------+
        ÿÿ1ÿ|ÿÿ1ÿÿÿ2ÿÿÿ3ÿÿ|
        ÿÿÿÿ+-------------+

        :ÿ
        :ÿend
        --------------------------------------------------------------------------------

        .ÿ
        .ÿsetÿlinesizeÿ`linesize'

        .ÿ
        .ÿexit

        endÿofÿdo-file


        .

        Comment


        • #5
          Yes, I realized this after i posted. Thank you.

          Comment

          Working...
          X