>> Home >> Features >> Overview >> Introduction to Mata

Introduction to Mata

Mata is a full-blown programming language that compiles what you type into bytecode, optimizes it, and executes it fast. Behind the scenes, many of Stata’s commands are implemented using Mata. You can use Mata to implement big systems, or you can use it interactively. Read about all of Mata's features.

To enter Mata, type mata at Stata’s dot prompt. To exit, type end at Mata’s colon prompt:

. mata
mata (type end to exit)
: sqrt(-4)
: sqrt(-4+0i)
: end

Mata supports real and complex numbers, binary and text strings (up to 2,147,483,647 characters long), and, for serious programming problems, even pointers!

Mata uses LAPACK routines for its advanced matrix features, such as Cholesky decomposition, LU decomposition, QR decomposition, SV decomposition, eigenvalues and eigenvectors, and solvers and inverters.

Mata supports matrices that are views onto, not copies of, the data. Say you have loaded a dataset of 200,000 observations and 150 variables, and you need a matrix of 80 of those variables in 180,000 of the observations. Rather than requiring 110 megabytes, Mata needs only 640 bytes.

Matrix languages evaluate matrix expressions, such as b=invsym(X'X)*X'y, and Mata is no exception. Because of Mata’s design, however, it is fast enough to work at the element level. Here is Mata’s polynomial solver:

numeric rowvector polysolve(numeric vector y, numeric vector x)
     numeric rowvector  res, c, empty
     real scalar        i, j, n

     if (cols(y) != cols(x) | rows(y) != rows(x)) _error(3200)
     if ((n=length(x)) == 0) _error(3200)
     res = (iscomplex(y) | iscomplex(x) ? 0i : 0)
     for (j=1; j<=n; j++) { 
         c = (1)
         for (i=1; i<=n; i++) { 
             if (i != j) { 
                 c = polymult(c, (-x[i],1) :/ (x[j]-x[i]))
         res = polyadd(res, y[j] :* c)
     while (res[cols(res)]==0) res = res[|1,1 \ 1,cols(res)-1|]

Much of Mata is written in Mata.

We recommend users begin reading Introduction and first session in Mata Reference Manual.

The Stata Blog: Not Elsewhere Classified Find us on Facebook Follow us on Twitter LinkedIn Google+ YouTube
© Copyright 1996–2016 StataCorp LP   •   Terms of use   •   Privacy   •   Contact us