Stata Matrices

Matrices are a fundamental data type in Stata, like scalars.

Note that Mata does not use this data type.


Description

Matrices are collections of numeric values.

Many commands return matrices; for example:

correlate foo bar baz, covariance
matrix cov = r(C)


Usage

To declare a matrix, try:

matrix A = (1, 2 \ 3, 4)
matrix input B = (5, 6 \ 1/3, _pi)

The matrix input subcommand allows for expressions as seen above, but otherwise does not differ.

Matrix elements can be accessed by subscripting (row then column) while indexing from 1. Following from the above example, A[1,2] returns 2.

To instead show the values of an entire matrix, try matrix list A.

To join matrices horizontally, try

matrix C = (A, B)

To join matrices vertically, try

matrix C = (A \ B)

A vector is simply a special case of a matrix.

Row and Column Names

A new matrix uses sequential names for rows and columns (i.e., r1, c1, and so on).

Commands that return matrices usually name the rows and columns. Commands that consume matrices often assume a common structure, and therefore require that specific names be used.

To assign names, try:

matrix rownames A = foo bar baz
matrix colnames A = ham spam eggs

Operators

Most operators work as expected. Note that the slash (/) performs element-wise scalar division.

New operators include:


See also

Stata manual section 14: Matrix expressions


CategoryRicottone

Stata/Matrices (last edited 2025-10-24 15:47:45 by DominicRicottone)