Mata

Stata supports an interpreted language with a matrix-based data model called Mata.


Data Types

To instantiate a scalar, the Mata concept for constants, try:

a=1
a="A"

To instantiate a row vector, try:

f=(1,2,3)
f=(1::100)
f=("A","B","C")

Or for a column vector, try:

g=(3\ 4 \5)
g=(1:100)
g=("A"\ "B"\ "C")

Matrices use the logical combination of this syntax.

h=(1,2,3\ 4,5,6\ 7,8,9)
h=("A","B"\ "C","D")

To combine vectors or matrices, try:

x=(1,2\ 6,7)
y=(3,4,5\ 8,9,10)
z=(x,y)

Matrix generation functions

J(r, c, a) returns an r x c matrix with every element being a.

I(r) returns an r x r identity matrix.


Stata Interoperability

Reading data

To read data from Stata's active session into a matrix, try:

q=st_data(., "numeric_var_name")
r=st_data(., ("numeric_var_name"))
s=st_data(,. ("numeric_var_1", "numeric_var_2", "numeric_var_3"))
t=st_sdata(., ("string_var_name"))

Note that string data needs to be read using st_sdata, not st_data.

The omission of the first parameter (or rather, supplying the missing value as the first parameter) indicates that we want all rows.

The second parameter can similarly be omitted, though this isn't as useful. Column selectors can either me numeric indices or variable names. Note that selection by numeric indices is faster computationally.

Writing data

To write a matrix into a variable in Stata's active session, try:

st_store(., "numeric_var_name", numeric_matrix_name)
st_store(., ("numeric_var_name"), numeric_matrix_name)
st_store(., ("numeric_var_1", "numeric_var_2", "numeric_var_3"), numeric_matrix_name)
st_sstore(., "string_var_name", string_matrix_name)

Note that string data needs to be written using st_sstore, not st_store.

Parameters are specified in the same way as st_data. Note that the function will raise an error if the selected matrix is not p-conformable (i.e. same dimensions) with the active session's data, so this flexibility is rarely useful.


CategoryRicottone

Stata/Mata (last edited 2023-06-08 00:38:05 by DominicRicottone)