Mata
Mata is a matrix programming language that is bundled with Stata.
Data types
Scalars store a single value, either numeric or string. To declare a scalar, try:
a=1 a="A"
Vectors are collections of values. All elements must be of the same data type; numeric and string values cannot be mixed.
To declare a row vector, try any of:
f=(1, 2)
f=(1::100)
f=("A", "B", "C")To declare a column vector, try any of:
g=(1 \ 2)
g=(1:100)
g=("A" \ "B" \ "C")Vector elements can be accessed by subscripting, with indexing starting at 1. Taking the above examples, g[1] returns 1.
To declare a matrix, combine these syntaxes.
h=(1, 2 \ 3, 4)
h=("A", "B" \ "C", "D")Matrix elements can be accessed by subscripting: row then column. Taking the above examples, h[2,2] returns 4. Furthermore, rows and columns of a matrix can be accessed like h[2,] or h[,2] (respectively).
To horizontally join vectors, try:
x=(h, g)
To vertically join vectors, try:
y=(h \ f)
Operators
Most operators work as expected, e.g. X*b performs matrix multiplication.
New operators include:
apostrophe (') for transposition, as in X'
Built-in functions
These functions operate on a matrix:
Name |
Meaning |
det(m) |
|
trace(m) |
|
inv(m) |
|
invsym(m) |
invert a symmetric matrix m |
These functions construct a new matrix:
Name |
Meaning |
I(n) |
return the n x n identity matrix |
J(r, c, x) |
return a r x c matrix with all elements set to x |
Stata Interoperability
To copy values from Stata's active, in-memory dataset into a matrix, try:
mymat=st_data(., ("foo", "bar", "baz"))The arguments to this function are vectors; the first is a column vector selecting rows of the dataset, while the second is a row vector selecting columns of the dataset. Generally the first argument is left as a missing value to mean copy all rows. Columns can be identified by either variable name or ordinal index. (Identification by index is technically faster.)
Note that string variables require the st_sdata function instead. It is used in the same way, however.
Note also that a different syntax can be used to copy a single variable. The following are equivalent:
mymat=st_data(., ("foo"))
mymat=st_data(., "foo")To then copy values from a matrix into Stata's active dataset, try:
st_store(., ("foo", "bar", "baz"), mymat)As before, string variables require the st_sstore function instead.
This function can raise an error if the selected matrix is not p-conformable (i.e., not the same dimensions) with the active dataset. Generally, it is necessary to clear the active dataset before attempting to copy values back.
