Announcement

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

  • How to repeat the 'rowsum' command to multiple matrix?

    Hello, forum users.


    I'm trying to data cleaning as follow


    mata

    K1995T[N02,N01] = rowsum(K1995T[N02,1::N]);
    K1995T[N03,N01] = rowsum(K1995T[N03,1::N]);
    K1996T[N02,N01] = rowsum(K1995T[N02,1::N]);
    K1996T[N03,N01] = rowsum(K1995T[N03,1::N]);
    .
    .
    .
    K2010T[N02,N01] = rowsum(K2010T[N02,1::N]);
    K2010T[N03,N01] = rowsum(K2010T[N03,1::N]);

    How can I make it shorter to use loop?

  • #2
    I see two ways, one in pure Mata, another with macros.
    Here is an example:

    Code:
    mata
    
    a1 = 1,2,3
    a2 = 4,5,6
    a3 = 7,8,9
    
    for (i=1; i<=3; i++) {
        p = findexternal(sprintf("a%f", i))
        (*p)[1] = (*p)[1]*10
    }
    
    a1\a2\a3
    end
    
    forv i=1/3 {
        mata: a`i'[1]=a`i'[1]*10
    }
    mata: a1\a2\a3
    By the way, you don't need to end lines with a semicolon.
    Last edited by Jean-Claude Arbaut; 27 Oct 2018, 03:18.

    Comment


    • #3
      Sasha: Here's an inelegant approach I often use for loops like this: Mata creates strings to pass to Mata's stata(.) function, which in turn does the Mata assignment.
      Code:
      mata
       
      s1="mata: K"
      s21="T[N02,N01] = rowsum(K"
      s22="T[N02,1::N])"
      s31="T[N03,N01] = rowsum(K"
      s32="T[N03,1::N])"
       
      for (j=1995;j<=2010;j++) {
       sj=strofreal(j)
       s2=s1+sj+s21+sj+s22
       s3=s1+sj+s31+sj+s32
       stata(s2)
       stata(s3)
      }
       
      end

      Comment

      Working...
      X