Matta Matters (excerpt)

From W. Gould (2007). Mata Matters: Subscripting. The Stata Journal, 7(1):106-116. https://www.stata-journal.com/article.html?article=pr0028.

This is a case of something difficult to program in Stata being trivial in Mata. The following example is well worth understanding.

: X
        1    2    3
    ┌────────────────┐
  1 │   4    7    9  │
  2 │   2   12    3  │
  3 │   8    8    7  │
  4 │   3    4    1  │
  5 │   1    7    9  │
    └────────────────┘

: uniformseed(39483)

: o = ceil(5*uniform(5,1))

: o
       1
    ┌─────┐
  1 │  2  │
  2 │  1  │
  3 │  5  │
  4 │  5  │
  5 │  2  │
    └─────┘

: Z = X[o,]

: Z
        1    2    3
    ┌────────────────┐
  1 │   2   12    3  │
  2 │   4    7    9  │
  3 │   1    7    9  │
  4 │   1    7    9  │
  5 │   2   12    3  │
    └────────────────┘

Below I use these ideas to perform a bootstrap of the regression of mpg on weight and foreign, using the automobile data:

. sysuse auto, clear
(1978 automobile data)

. mata:
───────────────────────────────────────────────── mata (type end to exit) ────
:     st_view(datay=., ., "mpg")

:     st_view(dataX=., ., tokens("weight foreign"))

:     n = rows(datay)

:     dataX = dataX, J(n, 1, 1)

:     N = 10000 // number of replications

:     uniformseed(47686)

:     b = J(N, 3, .)

:     for (i = 1; i <= N; i++) {
>         o = ceil(n*uniform(n,1))
>         y = datay[o,]
>         X = dataX[o,]
>         b[i,] = (invsym(X'X)*X'y)'
>     }

:     variance(b)
[symmetric]
                  1              2              3
    ┌──────────────────────────────────────────────┐
  1 │   3.10765e-07                                │
  2 │    .000172885     1.29395868                 │
  3 │  -.0010054771    -.645488234    3.355736044  │
    └──────────────────────────────────────────────┘

: end
──────────────────────────────────────────────────────────────────────────────

These results are similar to those that would be produced in Stata by typing estat vce after bootstrap, reps(10000): regress mpg weight foreign.