## Basic Matrix Algebra in STATA

The source of all wisdom on STATA matrix algebra is the STATA 9 User's Guide. The relevant pages are 159-170. Additional information on matrix functions is found in the STATA Data Management Guide.

All matrix commands begin with the word "matrix".

Vectors have no independent status in STATA. Vectors and matrices are treated identically.

(More complex matrix programing is possible using STATA's MATA programing language.)

* * * * * *

Creating Matrices in STATA

There are two ways to create matrices within STATA. Using the matrix command (which is shorthand for "matrix define"), a matrix may be input element by element. Alternatively, the mkmat command can be used to create a matrix from the variables of an existing data set by concatenating (joining) columns.

I. matrix name = (elements)

To input a matrix, enclose the elements of the matrix within parentheses with commas to separate elements and backslashes (\) to separate rows. (The number of columns is implied by the number of elements in each row.) . Thus (2,4,3,7\1,5,3,1) is a 2x4 matrix that looks like

```					2  4  3  7
1  5  3  1
```

and is created by the command "matrix A =(2,4,3,7\1,5,3,1)".

Row and column vectors are created with the same commands. The command "matrix A=(2,1,4,3)" creates a 1x4 row vector while the command "matrix A=(2\1\4\3)" creates a 4x1 column vector.

II. mkmat variable names, matrix(matrix name)

Matrices can also be created from the variables of an existing STATA data set using the mkmat command. The following command will concatenate the variables V1, V2 and V3 into a new matrix A composed of N rows (where N is the number of cases in the data set) and 3 columns, 1 for each variable:

mkmat V1, V2, V3, matrix (A)

Manipulating Matrices

```	matrix	C = A,B			Join matrices A and B columns by row.
(A & B must have the same # of rows.)

matrix	C = A\B			Join matrices A and B rows by column.
(A & B must have the same # of columns.)

matrix	A = J (#1, #2, #3)	Create a #1 by #2 rectangular matrix
with value #3 in all elements.

matrix 	I = I (#1)		Create a square identity matrix with
#1 rows/columns.

matrix	A = DIAG (V)		Create square matrix with values of
vector V as main diagonal, elsewhere 0

matrix	NR = ROWSOF (A)		Finds # of rows in A.

matrix	NC = COLSOF (A)		Finds # of columns in A.

```

Key Matrix Operators

```	matrix	C = A + B		Add matrices A and B.

matrix	C = A - B		Subtract matrices A and B.

matrix	C = A * B		Multiply matrices A and B.

matrix	AT = A'	 		Find the transpose of A.

matrix	INVA = INV (A)		Calculate the inverse of A.

matrix 	DETA = DET (A)		Calculate the determinant of A.

matrix	DIAGA = VECDIAG (A)	Create a column vector from
the diagonal of  matrix A.
```

Results

```	matrix 	LIST A	  		Displays dimensions and elements of A
```